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.

4
  • 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. Commented Jun 21, 2017 at 7:48
  • What is the error message when you try to store it to the global variable? Commented Jun 21, 2017 at 7:49
  • Possible duplicate of How do I return the response from an asynchronous call? Commented Jun 21, 2017 at 7:51
  • no error message however when I use console.log(postJson) outside the success, it shows up as "undefined" in the console. Commented Jun 21, 2017 at 7:52

2 Answers 2

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)     
      }
}); 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.