Saturday, April 7, 2012

Store ajax json response into javascript variable using jquery

If you wish to make an ajax call, and assign response json into a variable directly...here is a small hack :
function getJson(url) {
 return JSON.parse($.ajax({
     type: 'GET',
     url: url,
     dataType: 'json',
     global: false,
     async:false,
     success: function(data) {
         return data;
     }
 }).responseText);
}

var myJsonObj = getJson('myjsonurl');

12 comments:

  1. Has been 2 days that I'm trying to find how to do it! Great little trick! Thanks a lot and keep up the good work!

    ReplyDelete
  2. Thanks for sharing,
    Its work. Solved my easyui project using this. U r the best

    ReplyDelete
  3. thanks so much for this bit of code, really saved my butt on a project using json

    ReplyDelete
  4. useful trick, but if i want to set 'async' variable true, i am working on progress bar, and for this i have to set async:true, so in this case how can i save response to a varaible?

    ReplyDelete
  5. +10 sos groso 1 dia buscando esto!! magnifico!

    ReplyDelete
  6. I receive the JSON info successfully but it's unable to parse it, I get an error at "return JSON.parse($.ajax({" which tells me that it's "undefined" despite that I've asserted that success: function works and "data" contains a valid JSON object. Any idea why?

    ReplyDelete
  7. this is seriously useful, could you please explain a bit why this works, ive been frustrated over callbacks all day! all i needed was this thing. sorted my problem totally. thanks!!

    ReplyDelete