Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm having an issue returning a JSON from PHP to Javascript. Below is my PHP to create the JSON:

$environment[] = array('id' => $env, 'adjacencies' => $hostnames);

foreach($hostnames as $hostname) {
        $environment[] = array('id' => $hostname, 'name' => $hostname, 'data' => array());
    }

return json_encode($environment);;

When I print the json_encode environment to a text file, it comes back as:

[{"id":"Dev","adjacencies":["tb23","tbwag","tbvg","tbut"]},{"id":"tb23","name":"tb23","data":[]},{"id":"tbwag","name":"tbwag","data":[]},{"id":"tbvg","name":"tbvg","data":[]},{"id":"tbut","name":"tbut","data":[]}]

It seems that this is printing out properly but when I return it to the Javascript its coming back as undefined/null. Below is the javascript with the ajax call:

var ajax = new AJAX();
var args = "id=" + $("#apps").val() + "&env=" + node.id + "&nocache=" + (new Date()).valueOf();
ajax.connect("POST", "http://" + window.location.hostname + "/project/graph/host", args, function(json) {

var output = '';
for (property in json) {
    output += property + ': ' + json[property]+'; ';
}
alert(output);
});

I've obviously tried a lot of different things to get it to print out but haven't had any luck. In PHP, I've tried json_last_error and it came back as '0', which means that there isn't an issue with the JSON structure.

In the end, I'd like to use the following command in Javascript to continue building my graph:

var hostNodes = eval('(' + json + ')'); 

Any help is appreciated as to why I can't get this to come back!

share|improve this question
 
Where is $env and $hostnames? It's not there. I'll change my answer if you really just forgot to mention it and It's not the problem. –  Jonast92 Mar 13 at 13:41
 
These variables are working fine so I left them out; they are created in another function. For all intensive purposes in this example, they can be hardcoded. –  ad2387 Mar 13 at 13:43
 
The PHP works fine, you're obviously doing some mistake in the javascript. –  Jonast92 Mar 13 at 13:45
1  
what is the actual value of json before you run your loop? –  djjjuk Mar 13 at 13:46
 
You need to use JSON.parse(plainJsonText) in JS to get that object in javascript because even when you encode the data server-side, it returns a plain string, which javascript considers a plain string only, not any special JSON thing. So, you'll need JSON.parse ... –  ShuklaSannidhya Mar 13 at 13:47
show 2 more comments

2 Answers

up vote 1 down vote accepted

Keep your PHP code in an unique file that receives one post parameters, then construct the json array if it set, and at the bottom you can do

echo json_encode($json);
flush();

I'm not a professional with pure javascript and I'm not familar with your approach, but you should consider using jQuery, at least I'm going to suggest one way to receive an json array so that you can easily work with it (you also make sure that the data is json):

$.ajax(
{
    // Post select to url.
    type : 'post',
    url : 'myPHPAjaxHandler.php',
    dataType : 'json',
    data : 
    {
        'select' : true
    },
    success : function(data)
    {
        // PHP has returned a json array.

        var id, hostname;

        for(var i = 0; i < data.length; i++)
        {
            id = data[i].id;
            hostname = hostname[i].id;
            // Construct a string or an object using the data.

        }
    },
    complete : function(data)
    {
        // Optional.
    }
});

Like I say, It's there for you to decide whether you pick it up or not. It can become handy for complex projects.

share|improve this answer
 
But you are using JQuery and he is not –  Ateszki Mar 13 at 13:55
 
I understand, maybe I should just delete this, or allow him to see this and maybe he'll decide to pick it up. We might say that I'm just suggesting a library within the same language as he is using. –  Jonast92 Mar 13 at 13:57
 
Don't delet it, but edit your answer to clear this up. –  Ateszki Mar 13 at 14:02
 
Updated the answer. –  Jonast92 Mar 13 at 14:04
 
Hey Jonast92, I tried your solution but it's coming up with 'length' is null or not an object. So it seems to me that data still isn't coming back with anything for some reason –  ad2387 Mar 13 at 14:05
show 4 more comments

It looks like you're assuming that the data passed to the callback function will be your JSON already parsed into JS objects, but I don't see any indication that that would be the case; it's most likely the raw JSON data that must be parsed into JS objects using JSON.parse (NOT eval() - eval() is very dangerous, you should always prefer JSON.parse when working with true JSON data, as it will not permit XSS-style attacks as they are generally not "pure" JSON.)

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.