September 29, 2013

How to turn variable name into string in JS?

Jehan’s Question:

I am trying to write a convenience wrapper for console.log, and I would like to print any variables passed in along with their contents.

Can I turn a variable name into a string in js?

There is a possibility. And here is how

var passed_variable = '65'; // The actual variable
var varname = 'passed_variable'; // The name of the variable in another variable

Now, pass the varname around but not the actual variable. When you need to the value of the variable you can simply do :

console.log(varname, ' : ', window[varname]); // Outputs, passed_variable : 65

I hope you find a way not to use this. 🙂

Set content-type on blob

Chris Nolet’s Question:

We’re transferring a Blob (image) down a websocket and rendering it to a canvas on the other end.

When I use createObjectURL with the blob, I get this error:

Resource interpreted as Image but transferred with MIME type text/plain: "blob:https%3A//staging.app.io/23f53ce3-5a52-4e12-8686-190eb15a9ede".

We create the object URL using the following code. The blob is send via a standard websocket with socket.binaryType = "blob"; on the client side:

socket.onmessage = function(e) {
  var blob = e.data;
  var url = (window.URL || window.webkitURL).createObjectURL(blob);

  var image = document.createElement('img');
  image.src = url;
}

The only way I can think to address this error is to create a copy of the blob with the following code, but I don’t want to introduce the overhead of copying all the data:

var blob = new Blob([e.data], {
  type: 'image/gif'
});

The method gets called dozens of times per second.

Any ideas on how to set the blob content-type without creating a duplicate Blob object with new Blob?

You can solve this problem from the end you are delivering the image. This problem is happening because of the wrong content-type, so you should configure your server to send image with image headers.

If this was in PHP, you should have something like

header("Content-Type: image/jpeg");
echo $image_blob;
exit;

(Just giving you an idea)

In case of Node.js, though I am not an expert you can set the content type on the response object like:

app.get('/image.gif', function(req, res) {
  res.set('Content-Type', 'image/gif');
  res.sendfile('./image.gif');
});

insert </br> after comma with php

Vektor’s Question:

I array text from custom field “black, grey, white” with this code:

<?php global $wp_query; $postid = $wp_query->post->ID; echo get_post_meta($postid, 'colors', true); ?>

I want show me like this:

black</br>
grey</br>
white

It’s possible with PHP? Many thanks

Use str_replace():

echo str_replace(",", "<br />", get_post_meta($postid, 'colors', true));

Log in script load users name

User2827404’s Question:

ive just built a php and mysql log in script which forwards to a members area. I now want the members name that loged in to be displayed, somthing like welcome Stephen for example.

what would be the best way to do this?

ok this is my code once the submit button has been pressed:

`<?php

$host="localhost"; // Host name
$username="stephen2_phptest"; // Mysql username
$password="********"; // Mysql password
$db_name="stephen2_phptest"; // Database name
$tbl_name="registers"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];


// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM registers WHERE email='$myusername' and password='$mypassword'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:members.php");
}
else {
echo "Wrong Username or Password";
}
?>`

And this is the code for the members area:

`<?php

$host="localhost"; // Host name
$username="stephen2_phptest"; // Mysql username
$password="********"; // Mysql password
$db_name="stephen2_phptest"; // Database name
$tbl_name="registers"; // Table name

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
session_start();
if(!session_is_registered(myusername)){
header("location:index.php");

$myusername=$_POST['myusername'];
}
?>
<html>
<link rel="stylesheet" type="text/css" href="../php/css/styles.css">
<body>
    <div class="members-screen">
Login Successful</br>
Welcome [persons name to load here]<?php echo $_POST['myusername'] ?> <a href="../php/logout.php"> | Logout</a>
<div class="menu">
    <div class="menu-btn">
        <a href="">Home</a>
        </div>
        <div class="menu-btn">
            <a href="">Search</a>
            </div>
            <div class="menu-btn">
                <a href="">Messages</a>
                </div>
                <div class="menu-btn">
                    <a href="">Matches</a>
                    </div>
                    <div class="menu-btn">
                        <a href="">My Account</a>
                        </div>
    </div>
</div>
</body>
</html>`

Store the name on the session when the user logs in and use it when it is needed to be showed.

session_start();

// Your login process

if($valid == true) {
   $_SESSION['logged_user'] = 'stephen'; // Fetch name from database
}

Then where you need to show:

session_start();
echo $_SESSION['logged_user'];
September 26, 2013

Devil of a time with jQuery delegate and .not

James Emanon’s Question:

I’ve searched hi and low but couldn’t find a solution. I’ve tried everything.. but can’t get this thing to work.

NOTE: Can’t use “.on()” . Using an older version of jQuery that only supports .live/.delegate

basically, I have a very involved webpage.. and there are event handlers flying everwhere.. BUT, I basically want to attach a click event on the body BUT exclude certain id’s. Great. Figured it would be easy.

tried:

 jQuery('body').delegate('.not("#mainID #anotherID")','click', function(e){ 
    // do something
 })

 jQuery('body').delegate(':not(".class1 .class2")','click', function(e){ 
    // do something
 })

etc…

and a bunch bunch more.. basically, cannot get this thing to work. No matter what I do, the whole page is clickable.

when I do something simple like: Great it works.

 jQuery('body').delegate('#someID','click', function(e){ 
    // do something
 })

But that isn’t what i need. I need to basically allow for clicking on the whole body except for two subsets, smaller sections of the page. I figured this would be trivial.. but for some reason, just not working.

The two items I want to exclude are:
id: mainID w/ a class of “.class1”
id: anotherID w/ a class of “.class2”

another note: mainID sits outside of anotherID – two distinct sections of the page. Both divs.

Let me point out few things related to event delegation:

  1. First of all, use .on() function, .delegate() is deprecated.

  2. Second, .class1 .class2 will match class2 which is inside of class1

    jQuery('body').on('click', ':not(.class1, .class2)', function(e) { 
        // do something
    })
    

But, this is also not what you need, you need:

$(".class1, .class2").on('click', function() { return false; });

If you are using older versions of jQuery and for some reason cannot change it, use .live() or normal .click() handler:

$(".class1, .class2").click(function() { return false; });

Now, if you click on .class1 and .class2 nothing will happen. If you want to select only specific class within a id you can use #mainID .class1 as selector. Or with older event delegation:

jQuery('body').delegate(':not(.class1, .class2)','click', function(e){ 
    // do something
    // but this will execute on every where you click except .class1, .class2
})
September 17, 2013

Convert String in Array JQUERY

User2789569’s Question:

I have the data array return of the server :

data.arr = [[Date.UTC(2013, 9, 17),1],[Date.UTC(2013, 9, 18),5],[Date.UTC(2013, 9, 19),2],[Date.UTC(2013, 9, 20),4]]

    [0] "[Date.UTC(2013, 9, 17),1]" String
    [1] "[Date.UTC(2013, 9, 18),5]" String
    [2] "[Date.UTC(2013, 9, 19),2]" String
    [3] "[Date.UTC(2013, 9, 20),4]" String

I need to pass only value to a function that recepeit an array[i,y], i need that stay following; i need to remove the “”.

    [0] [Date.UTC(2013, 9, 17),1]
    [1] [Date.UTC(2013, 9, 18),5]
    [2] [Date.UTC(2013, 9, 19),2]
    [3] [Date.UTC(2013, 9, 20),4]

How to do it?

data.arr = [[Date.UTC(2013, 9, 17),1],[Date.UTC(2013, 9, 18),5],
[Date.UTC(2013, 9, 19),2],[Date.UTC(2013, 9, 20),4]]

This code should already give you a timestamp value, but I am assuming you are asking about when it is treated as string so as suggested in comments, you can use eval to evaluate the string as Data Object.

for(var i = 0; i < data.arr.length; i++) {
     data.arr[i] = [data.arr[i][0], eval(data.arr[i][1])];
}

Here is a demo: http://jsfiddle.net/8eLEH/

How to replace session_register() for PHP 5.4+

Michael Curving’s Question:

out of the blue I was getting the following error when logging in to one of my sites:

Call to undefined function session_register()

After some research I saw that session_register() is deprecated after PHP 5.4. I checked in my hosting control panel, and sure enough it says current version I’m running is PHP 5.4.19. I assume they just forced an upgrade which is why this problem seemed to occur out of the blue.

I looked through several Stack Overflow posts and reviewed links to PHP documentation. From what I gather, session_register() is deprecated and should be replaced with $_SESSION instead.

Problem is, both of those already appear in my code. Here is the code in my index.php file:

  53 <? if ($username) {
  54    session_register("ADMIN");
  55    $_SESSION['ADMIN'] = $username;
  56 ?>

So I hoped just by removing line 54 (the deprecated piece) then it should work, however that is not the case. It broke the code when I did that.

Based on other posts I read HERE and HERE they seem to be saying that the code I see in line 55 above should by itself do the trick. So I’m a bit confused why it didn’t work. If anyone can tell me what code I should use I would sincerely appreciate it. The developer of the script is not really offering support.

NOTE: Also, yes there is session_start() called at the very top of the page.

Add a session_start() at the begining of your code and $_SESSION to manipulate it or create it.

September 16, 2013

grouping multi-dimensional array in PHP

Devlin Carnate’s Question:

I have a multi-dimensional array, and I want to group it by org and then by dept. I have the first level of grouping working:

   $groups = array();
   foreach($inv_h as $item) {
       $groups[$item['org']][] = $item;
   }

How do I achieve the second level of grouping?

If thats how you are grouping the groups then:

   $groups = array();
   foreach($inv_h as $item) {
       $groups[$item['org']][] = $item;
   }

   $depts = array();
   foreach($inv_h as $item) {
       $depts[$item['org']][] = $item;
   }

   // Then combine these two array

   $merged = array_map(null, $groups, $depts); 

   // Now they are groups

How can I automatically add line breaks in a textarea?

Nubby’s Question:

I have a textarea that isn’t very wide. I want as the user enters text for there to be line break once a line has 50 characters. I don’t want any wrapped text. Just line breaks. Is there a way to make this happen?

I tried to test something basic out on one line and failed.

$('#textarea').keypress(function (e) {
if ($(this).val().length == 50) {
    $(this).val()[51] == 'n'
}
})

I clearly am not very experienced. I don’t know if I should start looking into the regExp object.

I can’t allow wrapped text because I need to measure what each line of the textarea has. After the user has submitted the form, I need to be able to use something like this:

var line = $('#textarea').val().split('n');
for(i = 0; i < line.length; i++){
    // do something
}

Try

$('textarea').keypress(function () {
  var length = $(this).val().length;
  if (length % 51 == 0 &&
      length > 0) {
    var val = $(this).val();
    $(this).val(val + 'n');
  }
});

http://jsfiddle.net/2QZbG/

You have use % to see if the length and multiple of 50 and add n at the end. Demo

if ($(this).val().length % 50 == 0) {
    $(this).val($(this).val() + 'n);
}
September 15, 2013

jsfiddle same codes display different results on html

Coding Freak’s Question:

I put http://jsfiddle.net/48Hpa/19/ same codes to HTML, but I get different results ……………………………………………………………………………………………………………………………………………….. why is that?

enter image description here

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>

    <link type="text/css" rel="stylesheet" href="style.css" />
    <link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.js"></script>

    <script>

        $(document).ready(function () {

            $(function () {
                $("#slider1").slider({
                    range: "min",
                    value: 36,
                    min: 12,
                    max: 36,
                    slide: function (event, ui) {
                        $(".amount1").val(ui.value);
                        writesum();
                    }
                });
                $(".amount1").val($("#slider1").slider("value"));
            });

            $(function () {
                $("#slider2").slider({
                    range: "min",
                    value: 50000,
                    min: 1,
                    max: 50000,
                    slide: function (event, ui) {
                        $(".amount2").val(ui.value);
                        writesum();
                    }
                });
                $(".amount2").val($("#slider2").slider("value"));
            });


            function writesum() {
                var months = $('.amount1').val();
                var credits = $('.amount2').val();
                var payment = parseFloat(Number(credits) / Number(months))
                var rounded = payment.toFixed(2);
                $('.amount3').val(rounded);
            }

        });

    </script>

</head>
<body>
     <input type="text" class="amount1" />

        <div class="container">
            <div id="slider1"></div>
        </div>

        <input type="text" class="amount2" />

        <div class="container">
            <div id="slider2"></div>
        </div>

        <div class="sonuccontainer">
            <div class="bilgilendirme">aylık ödeme miktarınız</div>
            <input type="text" class="amount3" />
        </div>
</body>
</html>

JsFiddle use a CSS reset file to reset all browsers default styling. That might be the cause.

But the blue is coming from your style definition:

.ui-slider .ui-slider-handle { outline-color: transparent; background: blue; position: absolute; top: -8px; left: -8px; z-index: 2;  border-radius: 70px;  width: 30px; height:30px; cursor: pointer; }

If it is not showing on your page, means there is something wrong in your page or the styles are being overridden.

Looking at your html, the CSS of jQuery Ui is loaded after your local CSS, so the styles from it are overriding your styles.css Switch them and put styles.css at last.

<link type="text/css" rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/smoothness/jquery-ui.css" />
<link type="text/css" rel="stylesheet" href="style.css" />
...

Please fill the form - I will response as fast as I can!