This is probably really stupid but i can’t find the problem with my code. It fetches a url that returns json and the function is then supposed to return a string:
function getit() {
var ws_url = 'example.com/test.js';
var user = false;
$.getJSON(ws_url, function(data) {
alert('user '+data.user);//shows john
user = data.user || false;
});
return user;//should return john but returns false
}
test.js will have something like this:
{"id":"12","username":"ses","user":"john","error":""}
or like this:
{"error":"123"}
I also tried if (data.user) {} else {} but it didn’t work either..
So what am i missing?
Thanks 🙂
The problem comes from the fact that the
$.getJSON()call is asynchronous. Once the ajax request is fired off, processing continues on insidegetit(), and your function immediately returns false. Later on, the Ajax response returns and setsuser, but yourgetit()functionreturned a long time ago!You can force the Ajax call to be synchronous using the
asyncoption, like this:If you do that, your browser will block on the script until the Ajax call returns. Generally this isn’t the ideal behaviour (which is why the default is
async: true), so I’d suggest reworking whatever it is that’s callinggetit(), and have it expect to process it’s results whenever it can, perhaps by passing it’s own callback function togetit()that would then be executed whengetit()is done.