Problem with getting JSON from PHP using AJAX

I got this problem when I wanted to get back a json produced in PHP. Naturally, I used this header:
header('Content-Type: application/json; charset=utf-8');

It did not work, and that’s the one that everybody said I should use. So I tried different. I tried this:
header('Content-type: text/plain; charset=utf-8');

And it worked! In FireFox, in Chrome, in IE 8 on my computer, but it failed on IE 8 on my co-workers computer. WTF? Yep. Somehow it failed, and it needed a fix.

Since it failed, I can tell you that in AJAX the return value was not the expected one. I used jQuery and expected the dataType: “json” to work. jQuery does the evaluation of the data and creates a JSON object. But not this time. It failed. In IE8 the header seemed to be ignored and the value returned was wrapped in <html><body></body></html> – and yes, it seemed to be a common error somehow, except that none of the solutions mentioned that seemed to work for others worked for me. I even tried some really simple code, and it failed – but I managed to get it to work if the filename actually was .json – but then I could not use PHP. Or could I? The solution was this, with two headers in PHP:

header('Content-type: text/plain; charset=utf-8');
header('Content-Disposition: inline; filename=response.json');

And then do the

echo json_encode($array);

And voila, it worked.

Advertisements

One Response to Problem with getting JSON from PHP using AJAX

  1. A.M. Doherty says:

    Ah, this is interesting. I’ve been working recently on a UX project that required some externally loaded JSON data.If the source was directly from ASP, with either:

    header(‘Content-type: text/plain; charset=utf-8’);

    or

    header(‘Content-Type: application/json; charset=utf-8’);

    jQuery would not treat it as a valid JSON object.

    Yet I could paste the direct output from the ASP into a flat file, call that file from the same routine and it would work perfectly every time.

    We have now changed the system to use cached output in a flat file for other reasons, but for my own peace of mind I’ll be checking to see if ‘Content-Disposition’ helps with a direct connection to the scripted version.

    Cheers, Anthony

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: