views:

60

answers:

2

I just want to get my PHP array to a JS array, what am I doing wrong here?

PHP:

// get all the usernames
$login_arr = array();
$sql = "SELECT agent_login FROM agents";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    array_push($login_arr, $row["agent_login"]);
}
$js_login_arr = json_encode($login_arr);
print $js_login_arr; // ["paulyoung","stevefosset","scottvanderlee"] 

JS:

var login_arr = "<?= $js_login_arr; ?>";
alert(login_arr); // acn't even get the string in??
var obj = jQuery.parseJSON(login_arr);
+1  A: 

Remove the quotes from the embedded PHP in your javascript. The notation is an array literal, and doesn't need quoting (assuming the PHP comment after js_login_arr is the what is printed into the javascript).

Chadwick
allright, thanks! what about parseJSON? I guess it's not valid JSON right?
FFish
login_arr is not valid JSON - it is already a valid Javascript object (an array of strings) so need not be parsed from JSON! If you really wanted to (but why?!), add quotes to the PHP embedded in your JS: `<?= '"'.$js_login_arr.'"' ?>`, but you'd also have to put backslashes prior to quotes within $js_login_arr itself... which just gets silly.
Chadwick
A: 

An easy way to do it is through delimiting. Take your array (don't use assoc arrays unless you need the field names), implode it into a string delimited by some character that shouldn't be used, say % or something, then in JS just explode on that character and voila, you have your array. You don't need to always use formalisms like JSON or XML when a simple solution will do the trick.

jMerliN
This suggestion is both fragile and adds unnecessary string processing - "some character" might well be in one of the strings of your list, screwing up the explosion. "Simple solutions" that involve string parsing are often where latent bugs lie. Besides, why create a string and explode to an array when you can simply create the array?
Chadwick
.split() e voila!!! That's a great tip Merlin, cheers.
FFish
oh, really no good than? I have to say... my login names are all validated, so I can safely use a certain delimiter. Also the array is rather small (less than 100)
FFish
It's only fragile if there's no good choice for a delimiter. The string processing in this solution places very little work on the server and will use less bandwidth than building the array in output or storing it in JSON or XML.Your point about the delimiter is both weak and unnecessary. By definition, the delimiter should be chosen so that it is not included in any string in the array.Also, in my code review I find more latent bugs in seemingly simple "construction loops" than I do in simple and proper library usage.
jMerliN