Ron Sarahan
Ron Sarahan

Reputation: 7

Getting Certain values from an AJAX return JSON object

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.

Upvotes: 0

Views: 69

Answers (2)

Nirav Joshi
Nirav Joshi

Reputation: 2960

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

Upvotes: 0

Kirill
Kirill

Reputation: 414

$.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)     
      }
}); 

Upvotes: 1

Related Questions