1

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

woshitom
  • 4,811
  • 8
  • 38
  • 62
  • Check you error_log. Maybe you will have an error in your json_encode. Maybe you will have special characters or the wrong encoding. – Tobias Jul 29 '15 at 08:10
  • thanks @Tobias I just did echo error_log(); but it doesn't retrieve me anything – woshitom Jul 29 '15 at 08:14
  • No error_log() will send an error message to the defined error handling routines. You should look into the error_log file where the PHP errors will be. – Tobias Jul 29 '15 at 08:17

4 Answers4

1
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

1

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

Edo San
  • 58
  • 8
1

Never forget the header!

<?php
header("Content-Type: application/json");
echo json_encode($tree);
koredalin
  • 446
  • 3
  • 11
0

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

Community
  • 1
  • 1
Alex Andrei
  • 7,315
  • 3
  • 28
  • 42