views:

11912

answers:

6

I've searched around and found two different ways to define Content-type for JSON file loaded with php.

header('Content-type: text/json');
header('Content-type: application/json');

which one should be used ?

+20  A: 

AFIK IANA has officially registered a MIME type for JSON as application/json in RFC4627, also is listed in the Internet Media Type list.

CMS
I see. I wonder what would happen if you use the wrong Content-type ?
andyk
@andyk: Depends on your client. For our web services, for example, our client library will accept non-standard text/json and x-text/json and a few others.
S.Lott
@S.Lott: I see, thanks for the info.
andyk
+3  A: 

Look at things like the Apache Axis spec. They favor application/json.

S.Lott
thanks. That's good to know.
andyk
+1  A: 

application/json is favored but usually web browsers don't know what to do with those headers and screws it up. For stuff like jquery, I have seen text/html recommended. If you are having errors pop up (e.g. download dialog box) then try text/html

codeo008
+4  A: 

I recently had a very strange run in with this.

I had a form which used jQuery to do an AJAX lookup against a PHP script, and then return the response as JSON, formed using PHP's json_encode() function.

It was all working fine for a couple of months, then this morning it stopped working... It turns out the javascript couldn't parse the JSON correctly.

My original method used eval.

I.e. var p = eval('(' + msg + ')');

But that gave me the error: missing ] after element list

I then tried using var p = JSON.parse(msg);

Using the json2.js library from json.org. This also failed.

I checked my JSON was formatted correctly using an online tool - it was.

In the end I tried changing the header type I was setting in the PHP script which was being called by jQuery AJAX.

I changed it from application/json to text/plain

And both the eval() and the JSON.parse solutions immediately worked... Much to my relief as I was running out of ideas.

Very odd and still don't know quite why, but thought I'd post here in case someone runs into a similar issue, or anybody can provide an explanation.

Tom
A: 

Thanks for this, been struggeling a few days. I still don't understand why IE7 only accepts text/plain. But all my stuff also works in IE7 now, i'm happy!

Jeroen
You really should put this in the comment, but you're welcome. I'm glad that my question could help someone. :)
andyk
A: 

How to configure this script to access localhost web service written in rails? I want to post something like this in json: { post: { title : 'HelloAndroid' } }.

Thanks in advance

Daniel