0

I'm trying to pass an array to Javascript after it has sent a GET request to PHP. Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:

<?php

$result = mysql_query('blablabla');

//converting $result to an array?

echo $result_as_javascript_array;

?>

<script>
$('result').innerHTML = httpGet.responseText
</script>
user1826176
  • 309
  • 2
  • 14

5 Answers5

2

Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.

On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?

And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated

Community
  • 1
  • 1
Jan Hančič
  • 53,269
  • 16
  • 95
  • 99
0

You are looking for json_encode.

cem
  • 3,311
  • 1
  • 18
  • 23
0

Use json_encode like this:

<?php

$result = mysql_query('blablabla');

//converting $result to an array?

echo json_encode($result);

?>

You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.

Joshua Dwire
  • 5,415
  • 5
  • 29
  • 50
0
$arr = array();
while ($row = mysql_fetch_array($result)) {
    $arr[] = $row;
}
echo $arr;

However, mysql_ is deprecated, use mysqli instead.

If you want to pass it as JSON, use this:

echo json_encode($arr);
looper
  • 1,929
  • 23
  • 42
0

you should use json_encode, which works fine, when directly assigning output to a javascript variable

<?php

$result = mysql_query('blablabla');

//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
    $myarray[]=$fetch;
}

//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>

<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
Kemal Dağ
  • 2,743
  • 21
  • 27
  • note that, assignin json string directly to a javascript variable is not safe, this is only for testing purposes, for serious development, you must use a JSON decoder for javascript, namely you can use Jquery's (var obj = jQuery.parseJSON('{"name":"John"}');) parseJSON function. – Kemal Dağ Nov 27 '12 at 14:49