0

I am trying to call an ajax request to my server for json data using a function. If I console out the resp variable inside the ajax function it will show the data successfully. If i try to set the ajax function to a variable, and then console that variable it returns undefined. Any ideas who to make the function request the data and then set ti to a variable to be consoled?

function jsonData(URL) {
var xhr = new XMLHttpRequest();
xhr.open("GET", URL, true);
xhr.onreadystatechange = function() {
  if (xhr.readyState == 4) {
    var resp = JSON.parse(xhr.responseText);
    return resp;
  }
}
xhr.send();
}

jsonString = jsonData(http://mywebsite.com/test.php?data=test);

console.log(jsonString);

1 Answer 1

3

This is actually pretty simple.. Change your call to by synchronous..

xhr.open("GET", URL, false);

That being said this will block the browser until the operation has been completed and if you can use a callback instead it would likely be preferred.

function jsonData(URL, cb) {
  var xhr = new XMLHttpRequest();
  xhr.open("GET", URL, true);
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
      var resp = JSON.parse(xhr.responseText);
      cb(resp);
    }
  }
  xhr.send();
}

jsonData("http://mywebsite.com/test.php?data=test"
        , function(data) { console.log(data); });
Sign up to request clarification or add additional context in comments.

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.