ajax, retrieve a multidimensional php array as a json - php

An Ajax call is computing me a multidimensional PHP array '$tree', after this call is made I would like to retrieve this array as a JSON.
My PHP page is only printing the Array:
print_r(json_encode($tree));
Here the success part of my ajax call:
success: function(data, textStatus, jqXHR) {
var myObject = JSON.parse(data);
alert(myObject);
}
Unfortunately the alert box is not triggered.
Also, I noticed that when I'm reaching my PHP page through a web browser:
print_r(json_encode($tree));
isn't displaying anything, while:
print_r($tree);
Is printing my multidimensional Array

echo json_encode($tree);
exit;
This is the ideal way to send JSON back to browser.
Also check that you do not have any special characters in your array otherwise you will have to use BITMASKs in json_encode function.
Also, All string data must be UTF-8 encoded, so you may want to correct the encoding of your data.
Further reading: http://php.net/manual/en/function.json-encode.php

As others already said, the correct method to output a JSON from PHP is via the json_encode function.
echo json_encode($tree);
You should probably check the encode of the Array data; if you have any string they must be encoded in UTF-8. I suggest you to loop through the $tree Array and to force the encode via the utf8_encode function (you can find PHP docs here).
If your Array has a depth of 2 levels you can try something like this, or some kind of array walk loop.
for (i = 0; i < count($tree); i++)
{
for (j = 0; j < count($tree[$i]; j++)
{
utf8_encode($tree[$i][$j]);
}
}
You probably just need to encode strings, so you should reduce the amount of data to encode if you can (i.e. you know that only 2 indexes in the whole array could be strings, or maybe could contain characters that need to be encoded).

Never forget the header!
<?php
header("Content-Type: application/json");
echo json_encode($tree);

First of all you need to test if the function json_encode exists.
if (function_exists('json_encode')) print 'json_encode working';
else print 'json_encode not working';
If it doesn't, you need to enable it, see here https://stackoverflow.com/a/26166916/5043552
Last, use print json_encode($tree) instead of print_r(json_encode($tree)).

Related

PHP Unserialize data for use in array - sub standard characters in string

I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517

Json_encode for .post?

can anyone explain the purpose of json_encode when doing a .post query.
This is what i often see in other's coding.
.post php script
...
...
echo json_encode($a);
I mean if i want to do a return from a .post script and returning an array via .post. Wouldn't i just need to do the following?
.post php script
...
...
$a = array("foo", "bar", "hallo", "world");
$string=implode(',',$a) in my php script
return $string;
javascript
$.post('$url',function(data){
data_arr=data.split(',');
//After which just get the values in the array
alert(data_arr[0]); //ALERTS 'foo'
alert(data_arr[1]); //ALERTS 'bar'
});
If anyone can just help by clearing this up for me and let me see the light for using json in this purpose, that would be great.
Perhaps its also due to my inept knowledge of JSON as well.
Would greatly appreciate it if anyone can advise me on why is it better to use JSON encode in this case and how am i suppose to use it via a .post request instead of just echoing out the string and split it later.
Thanks.
Using json_encode ensures that your data is always valid.
It doesn't really matter for simple data that you have control over, though imagine if someday you have a comma inside one of the values. With JSON encoded strings, you don't have to worry about an arbitrary separator token.
Also, with JSON you can easily encode Objects/Arrays without needing to reinvent the wheel.
First of all, in my opinion and practise, JSON syntax is fairly similar to Javascript objects and it's great when dealing with more complex data types that have to be sent/requested and parsed later on.
For example:
If you're doing a post request and you're serializing all the form fields which you validate server side (using PHP) you're most likely going to need to use key => value pairs like textbox_name => value. It's more logical to do it that way, than to select values by numeric indexes (what if the form layout changes?)
Example code using commas:
<?php
$array = array('Tom', 'Hanks', 'Football');
$string = join(',',$array);
echo $string; //it's obvious - the output is Tom,Hanks,Football
?>
The javascript that receives the string
$.post(url,{},function(data){
var values = data.split(',')
$("#name").text(values[0]);
$("#surname").text(values[1]);
$("#interests").text(values[2]);
});
So it makes sense right? But wouldn't it more sense to do this instead:
<?php
header('Content-type: application/json');
$array = array('name' => 'Tom', 'surname' => 'Hanks', 'interests' => 'Football');
echo json_encode($array);
?>
And the javascript:
$.post(url,{},function(data){
for(index in data) {
$("#"+index).text(data[index]);
}
//or
$("#name").text(data.name);
$("#surname").text(data.surname);
$("#interests").text(data.interests);
});
The same goes with parsing response data with Javascript. Having an object is more logical than having a CSV string.
Obviously it depends on the use case, but in general JSON gives you a logical structure of stringified Objects/Arrays which can be translated back into objects and arrays and looped through or manipulated in any way.
Also JSON is now a standard. Everyone uses it which means that it's not for no reason.
In other words - JSON data makes more sense.

Pass PHP Array to Javascript

Am trying to pass an array of values from PHP function to Javascript. Not sure if I am doing it correctly.
PHP:
function toggleLayers(){
for($i=0;$i<$group_layer_row;$i++){
$toggleArray=mb_convert_encoding(mssql_result ($rs_group_layer, $i, 0),"UTF-8","SJIS")."_".mb_convert_encoding(mssql_result ($rs_group_layer, $i, 1),"UTF-8","SJIS");
return $toggleArray;
}
}
JS:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
for(var i=0;i < myArray.length; i++){
if($myArray.getVisibility()==true){
$myArray.getVisibility(false);
}
else{
$myArray.getVisibility(true);
}
}
SQL (for reference):
$con = mssql_connect("myServer", "myUsername", myPassword");
$sql = "SELECT * FROM m_group_layer WHERE group_id=\"".$_SESSION["group_id"]."\" ORDER BY display_order";
$rs_group_layer = mssql_query ($sql, $con);
$group_layer_row = mssql_num_rows($rs_group_layer);
I have been looking at some other similar questions, and the answers are either vague and/or there are a few thousand of them.
Would appreciate any help, also please try to explain as if you were writing a book called "Idiot's Guide to Passing PHP Arrays to JS"
Thanks for your help.
Edit:
Sorry, my question was very vague. Here's what I'm trying to do:
1.PHP Function gets all records from table into array(in this case they are map layers)
2.Javascript receives PHP array and loops through adding if clause to toggle layers.
Hope this makes it clearer.
It's simpler than you think.
Change this line:
var myArray = [JSON.parse("<?php echo json_encode($toggleArray); ?>")];
To just:
var myArray = <?php echo htmlspecialchars(json_encode($toggleArray), ENT_NOQUOTES); ?>;
json_encode produces a json string. Echoing the string into a javascript context is the equivalent of a javascript literal. The htmlspecialchars is just for the necessary html escaping and is not unique to echoing json.
NOTE however that you can only json_encode a php object or array, not any scalar types like ints or strings. This is a limitation of JSON itself. In your toggleLayers() function, you are returning a string, not an array.
A thing that would be very useful to understand:
You sumply can't "pass an array of values from PHP function to Javascript".
But rather you have to create the javascript code using PHP just like you are creating HTML.
Thus, 3 simple step to solve any problem with PHP -> client transfers:
Create a pure client-side code you wish. Make it work. Save it somewhere.
Create a PHP code to produce that client-side code.
Compare the codes. If doesn't match - correct the PHP code. Repeat until done.

PHP Array to jQuery array with JSON. ($.post, parseJSON, json_encode)

I am trying to get a php file setup to return the results of a MySQL database query from a jQuery AJAX call. The returned results will be an array. I have a very basic start where I am just getting some basic data back and forth to and from the php file, but am stuck with some basic syntax issues:
The PHP code:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
The jQuery code:
$.post("dbFile.php", str, function(theResponse){
alert('the response: ' + theResponse);
var obj = $.parseJSON(theResponse);
alert(obj.a);
I can print out obj.a, obj.b, obj.c... no problem. The problem is I will be incrementing a counter as I increment through the MySQL results. So, the array does not use letters, it uses numbers:
$arr[$i] = mysqlresults ... $i++;
So, in the JavaScript/jQuery I have an object (not an array). I can print out obj.a for example, but I can not print out obj.2 (for example). In other words, if I replace the letters with numbers in the php array, I don't know how to print them out in JavaScript/jQuery. Can I change the object that parseJSON returns into an array somehow (so that I can cycle through it)?
Use the array access syntax:
alert(obj[42]);
You can use:
alert(obj['a']);
See this question for more info.

Getting array to .ajax on success

I'm trying to return data as an array to my .ajax function on success so I can do do multiple things, but I can't get to work for anything except a single value. Like return $foo. But when I return $array, the page never loads up.
JavaScript's use & utilizing of array is different as compared to PHP's processing. So, either you need to send the data to your AJAX function as a JSON (JavaScript Object Notation), otherwise you need to send the data as a string with a common separator to your AJAX function.
In the latter case, you will need to split up the Response Text in your AJAX function, with that common separator, to make up a JS Array. Then it will be very much easy to use that array instead.
Hope it helps.
You would have to serialize your data into a string. My preference is JSON, so if your PHP version is >= 5.2.0, you'll most likely have access to a json_encode function. This will turn the PHP object into a JSON string. If you don't have access to json_encode, you can use the PECL JSON package.
Looking at the way you reference your ".ajax" function, I am assuming jQuery. So as long as you set the content type to 'json', the JSON response will result in a native JavaScript object. For example,
PHP,
return json_encode(array(1, 2, 3));
JavaScript,
$.ajax({
...
contentType: 'json',
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i]);
}
});
This code should proceed to alert 1, 2, and then 3.
I haven't verified the code, but the essential parts are all there. A note to have though, a normal indexed array is turned into a JavaScript list while an associative array will be turned into a JavaScript object.
JSON is a good option to send your data array from PHP to Javascript. In PHP side just encode and return your data array as JSON string and in the Javascript side decode that JSON string and use as normal array.
Suppose your data array is like $array, in your PHP code just encode that array using json_encode($array) and return the resulted JSON string.
In your javascript code decode that JSON string using 'eval' function in the success callback function like:
$.ajax({
type: "GET",
url: "test.php",
success: function(data) {
var dataArray = eval('(' + data + ')');
}
});
I think this will help you ...
Siva

Categories