0

I wants to load JSON from my server and use it using jQuery. So, I wrote some source code. Here's my code:

var myData;
$.ajax({
    url: "https://httpbin.org/get",
    success: function (json) {
        myData = json;
    }
});
console.log(myData);

I think console should say JSON value. But when I run this code, console says it's value is undefined. What's wrong?

youngminz
  • 1,364
  • 2
  • 14
  • 23

1 Answers1

0

An ajax call is asynchronous, try :

var myData;
$.ajax({
    url: "https://httpbin.org/get",
    success: function (json) {
        myData = json;
        console.log(myData);
    }
});

EDIT :

Javascript is synchronous, it's ajax call who isn't, at the time you ask for an Ajax request, Javascript launches the call then continue to read your code. The Ajax response comes when the server responds. If you want your code to be synchronous you can write :

var myData;
$.ajax({
    url: "https://httpbin.org/get",
    success: receivedDatas
});
function receivedDatas(res){
    myData = json;
    console.log(myData);
}

Then your JS will do nothing until a response comes

RE-EDIT :

To complete the answer as @fiddler wrote :

Note that $.ajax() has a async parameter (true by default) which you can use to make it synchronous (see api.jquery.com/jquery.ajax)

Sacreyoule
  • 180
  • 9