PaddyREC
PaddyREC

Reputation: 67

How to store JSON response into JavaScript

I'm trying to store the JSON response in to variable so that I can process it later, i tried with following but getting null,

function go(){
   var jsonObj = getJson(url);
   alert(JSON.stringify(jsonObj));
  }

function getJson(){
    return JSON.parse($.ajax({
        type: 'POST',
        url: 'url',
        dataType: 'json',
        global: false,
        async: false,
        success: function(data){
        return data;
        }
    }).responseText);
}

mean time i can see the JSON content getting printed on my server console.

EDIT

Thannks rid..! that fixed the issue. you solution works fine in IE8, but for Chrome and FireFox still getting 'null' in alert pop-up. i don't think its browser specific fix..?

Upvotes: 0

Views: 2938

Answers (1)

mpm
mpm

Reputation: 20155

$.ajax({
        type: 'POST',
        url: 'url',
        dataType: 'json',
        global: false,
        async: false,
        success: function(data){
         // do some stufs or assign data to a var
         window.myVar = data;
        }
   });

Ajax is asynchronous ,so you need to store the response in a variable in the callback. in this exemple , window.myVar is a global variable that will contain the response data. You cant access the variable until a response has returned , you'll need to write async code.

Upvotes: 1

Related Questions