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>
3
  • 1
    You can use json for this kind data. Commented Nov 27, 2012 at 14:40
  • 4
    json_encode() : ie1.php.net/manual/en/function.json-encode.php Commented Nov 27, 2012 at 14:41
  • you can look into json to pass an array of data back through to javascript Commented Nov 27, 2012 at 14:41

5 Answers 5

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: https://www.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated

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>
1
  • 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. Commented Nov 27, 2012 at 14:49
0

You are looking for json_encode.

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.

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);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.