views:

116

answers:

3

I am making a jquery sychronous call to ajax -- with the return type set to "json" -- however the return data is comming back as a string. Is there something I'm doing wrong, or is there away to convert the string to an object?

var ajax_response = $.ajax({url:"ajx_services", async:false, type:"post", data:{method: "getItem", item_no: $(ctx).val()}, dataType:"json"});
var data = ajax_response.responseText;

The ajax call is working, as I can see the results in the debugger, it is simply that the returned data is in a string.

+1  A: 

responseText will always be a string. within $.ajax() add a 'success' callback function with a parameter and that will be the JSON data.

$.ajax({
    -- other stuff --
  , success: function(data)
    {
        // do something with data
    }
});
Darrell Brogdon
+1  A: 

That is because $.ajax() will return an actual XMLHttpRequest .. whose responseText has no concept of JSON etc.

Try this:

var data = (function () {
 var ajaxResponse = '';
 $.ajax({url:"ajx_services", async:false, type:"post", data:{method: "getItem", item_no: $(ctx).val()}, success: function (data) {
  ajaxResponse = data;
 }, dataType:"json"}); 
 return ajaxResponse;
}());

Since ajaxResponse is defined in the parent closure of the function defined in the ajax() call, it can be set to the JSON data object that is provided by the success function (which is called when the Ajax request successfully completes). Then, ajaxResponse is returned by the parent closure, which is then assigned to the outside data variable.

Note that this ability to immediately return the modified ajaxResponse from the ajax() is only possible because the request is synchronous. If it were async, return ajaxResponse would very likely return an empty string.

Matt
Thanks!! ... worked like a champ; I was wrongly suspicious of the success function with the async:false.
A: 

That way should work, using the eval function:

var ajax_response = $.ajax({url:"ajx_services", async:false, type:"post", data:{method: "getItem", item_no: $(ctx).val()}, dataType:"json"});
ajax_response.onreadystatechange = xHandler;

function xHandler() {
  if (ajax_response.readyState == 4) {
    var data = eval('(' + ajax_response.responseText + ')');
  }
}

But as it has been said before, you should use jQuery success callback, which exists to make your life easier.

dasilvj