Passing PHP array to Javascript via GET - php

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>

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

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>

You are looking for json_encode.

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.

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

Related

Echo/return an array in php

Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function.
Calling Jquery:
$.post(url, data, function (data)
{
alert(data);
})
relavent PHP:
$sql = "Select * from location";
$result = mysql_query($sql);
$stack = array();
while($row = mysql_fetch_array($result))
{
array_push($stack, $row["userLOC"]);
}
return $stack;
The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP
$foo = array();
echo $foo;
will produce the literal string Array as output.
You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so:
$foo = array('a', 'b', 'c', 'd', 'e');
echo json_encode($foo);
Then in your JS code:
$.get(...., function (data) {
alert(data[1]); // spits out 'b'
});
Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data.
Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON!
Client-side:
jQuery.post(url, data, function( data ) {
//Data is already converted from JSON
}, "json");
Server-side:
return json_encode($stack);
Explanation
Hope this helps!
echo json_encode($stack); can help you
at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript:
return json_encode($stack);
As others have said, you may wish to wrap the output using something like json:
echo json_encode($stack);
However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list:
echo implode(',',$stack);

Encode HTML for JSON string

I am storing html in a mysql database as raw html. I am pulling the contents and placing it into an array as follows. The array is the json_encoded, but if there is any double quotes or urls then the javascript displaying the JSON string breaks.
Is it possible to encode html to work through JSON?
Here is an extract of what I am using
<?php
$rows = array();
$sql ="SELECT html FROM table";
try {
$sth = $dbh->query($sql);
while($r = $sth->fetch(PDO::FETCH_OBJ)) {
$rows[] = $r;
}
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that. $e";
}
?>
var json = JSON.parse('<?php print json_encode(json_encode($rows)); ?>');
The json string currently outputting throws a javascript error saying unexpected <
[{"html":"<a href="http:\/\/www.url.com">\n<img src="http:\/\/www.url.com\/img\/logo.png">\n<\/a>"}]
Please no lectures on why this may be a bad thing. This is what my client has requested specifically and I just need to know if it is possible.
I agree with Mark B's answer but you could use fetchAll() and json_encode() the result of this function. Why do you use PDO Object fetching instead of array fetching?
<?php
$rows = array();
$sql ="SELECT hmtl FROM table";
try {
$sth = $dbh->query($sql);
$rows = $sth->fetchAll(PDO::FETCH_ASSOC);
}
catch(PDOException $e) {
echo "I'm sorry, Dave. I'm afraid I can't do that. $e";
}
?>
var json = <?= json_encode($rows); ?>;
Moreover consider getting it via AJAX.
There's no need for the json.parse business. JSON IS valid javascript after all, so a simple
var json = <?php echo json_encode($rows); ?>;
is all you need.
The line
var json = JSON.parse('<?php print json_encode(json_encode($rows)); ?>');
...is susceptible to single quotes in the resulting JSON (and other things; you'd have to double-escape lots of stuff). But you don't need or want to do that. Do this:
var json = <?php print json_encode(json_encode($rows)); ?>;
json_encode returns valid JSON, and JSON is a subset of JavaScript object initializer syntax, and so the above will result in valid JavaScript code describing the object. If you're outputting JavaScript code, as you appear to be from that line, there's no reason to go indirectly through a string. And as you've found, there's a reason not to.
Before filling the JSON object, you could use htmlentities() to convert all applicable characters to HTML entities, and then when printing them out just use html_entity_decode() if you use an ISO standard as character set. Sorry if I might have misunderstood the question.

How to format JSON output to display only values in quotes and not keys?

This is related to Need to display only array value in JSON output asked earlier.
I just want to show only values like
[
"autoComplete",
"ColdFusion",
"jQuery Mobile"
];
Background:
I am using and AJAX call via Jquery mobile to retrieve data from server (language:PHP). I want to use https://github.com/commadelimited/autoComplete.js in my Phonegap Application.
Please advice! I am new to JSON.
when using json_encode, any array that has a zero based numeric index (meaning it is not an associative array and starts with 0 and is not missing any numbers) will be converted to a javascript array instead of a js object literal. You can use array_values in php to get all the values from an array numerically indexed.
<?php
//a generic array
$a = array(
'foo'=>'bar',
'one'=>'two',
'three'=>'four');
//display the array in php
var_dump($a);
echo '<br>';
//json encode it
$json = json_encode($a);
var_dump($json);
echo '<br>';
//json encode just the values
$json = json_encode(array_values($a));
var_dump($json);
http://codepad.viper-7.com/hv06zn
Thanks Jonathan.
However I found the solution as below. I hope that it is useful to someone else too.
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row["title"];
}
mysql_close($con);
echo json_encode($records);

PHP, JSON, and MySQL

What is the easiest way to retrieve data from the database, and convert the data to a JSON String?
Is there any kind of helper class? or am I supposed to loop through the columns in my dataset to create the JSON string?
You can use the json_encode function to convert a native PHP array or stdClass object to it's corresponding JSON representation:
$result = $db->query('SOME QUERY');
$set = array();
if($result->num_rows) {
while($row = $result->fetch_array()) {
$set[] = $row;
}
}
echo json_encode($set);
Make an array from mySQL, and json_encode() it
Yes, use PHP's functions to handle JSON encoding.
Here's an example I got from this SO question:
$sth = mysql_query("SELECT ...");
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
print json_encode($rows);
Have you seen the json_encode() function? It takes an array as input and outputs JSON. So the most basic would be a two-dimensional array representing your table as input to json_encode
If you use the json_encode function then you're depending on somebody else's interpretation of the right way to format the json. Which means that you might come out with weird json, or have to contort your classes in evil ways to make the json come out right.
Just something to think about.

PHP array to JS array with jQuery and json_encode

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);
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).
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.
If you want to make php array to JSON you have to do this if $phpArray is actually an array.
var jsJSON = echo json_encode($phpArray)
If you want just to echo and turn to JSON you have to give it like a string:
$phpArray = '{'.$key1.':'.$val1','.$key2':'.$val2.'}';
This will work for sure.

Categories