0

I am trying to retrieve certain values in a JSON object retrieved from AJAX.

Using console.log(), I was able to view these:

0: Object
   title: "First post"
   body: "This is a post"
   id: 1
   userId: 27
.
.
.
100: //same format of data as object 0

Now I want to try storing the whole JSON object above so that I can use the userId and match it with another list of data to find the user who made the post. Problem is, I can't store it to a global variable. Here is my jscript snippet:

var postJson; //global variable

---somewhere in a function---
$.ajax({
      url: root + '/posts',
      type: "GET",
      dataType: "JSON",
      success: function(response){
      postJson = response;
        console.log(response);                 
          }
      });  

I also tried doing postJson = $.ajax but nothing happened and postJson continues to be undefined.

piet.t
  • 11,718
  • 21
  • 43
  • 52
  • You might be trying to use `postJson` variable, before your ajax response has been received. I think if you console it inside the `success` handler, you would print the expected json object. – Mohit Bhardwaj Jun 21 '17 at 07:48
  • What is the error message when you try to store it to the global variable? – shole Jun 21 '17 at 07:49
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  Jun 21 '17 at 07:51
  • no error message however when I use console.log(postJson) outside the success, it shows up as "undefined" in the console. – Ron Sarahan Jun 21 '17 at 07:52

2 Answers2

1

$.ajax is async function, you need to use callback or do all the code in success function

var postJson; //global variable

function doSomething(r){
    //r is here
}

---somewhere in a function---
$.ajax({
      url: root + '/posts',
      type: "GET",
      dataType: "JSON",
      success: function(response){
          postJson = response;

          //do something with postJson or call function doSomething(response)     
      }
}); 
Kirill
  • 414
  • 7
  • 16
0
function doSomething(r){
    //r is here
}

---somewhere in a function---
$.ajax({
      url: root + '/posts',
      type: "GET",
      dataType: "JSON",
      success: function(response){
      doSomething(response);
          //do something with postJson or call function doSomething(response)     
      }
});

You can do directly via calling function from response no need to declare variable. Hope it will also helps you

Nirav Joshi
  • 2,924
  • 1
  • 23
  • 45