How to get JQuery to accept a JSON reply? How to get JQuery to accept a JSON reply? json json

How to get JQuery to accept a JSON reply?


I did have similar problem as you have mentioned when using $.POST().There are two things if you are using jquery $.post method. You need to add an extra bracket before defined data type ("JSON") as shown below. I don't know why but it works, it will return data.

$.post('server.fcgi', {}, ajax_callback,{}, 'json');

The second thing is that you will need to parse JSON data using $.parseJSON(data) in side the callback function.

One more thing to make sure that the url to fetch JSON, the page document type should be defined as JSON in the header.

I have given an example below.

$.post("url/path/here/to/json", {}, function(data){    if(data){ // just in case the called program had a problem         var obj =  $.parseJSON(data);        .... do everything else using the Obj->             }},{},"json");

This will work.

However I recommend to you to use another Jquery function specially implemented for JSON, that is called

$.getJSON();

Here is the url for more information

And I am suggesting you to use the following method instead of the one described by you.

$(document).ready(function(){    $('.clickable').live('click', function() {              $.getJSON('server.fcgi', function(data){                         window.location.hash = data.h1;              });         }    );});


Make sure the server also returns the correct HTTP headers before the payload. E.g.:

HTTP/1.0 200 OKContent-Type: application/jsonContent-Length: ......{"h1":"bla"}

From your description, I could not quite make out if all it did was printf("{\"h1\":\"bla\"}"); or not.

To check the actual result, use a command line tool like HEAD, GET, wget, curl, or even nc. If you are not able to use one of those, you might get some clues from the Net panel in Firebug and the like.


Probably not the answer you want to hear, but I assume you're using jQuery 1.4.2? I noticed that this does work as expected in 1.3.2 so you might want to consider using that instead. :(