fetching a url using $.getJSON and parsing it correctly

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 :)

Answers


The problem comes from the fact that the $.getJSON() call is asynchronous. Once the ajax request is fired off, processing continues on inside getit(), and your function immediately returns false. Later on, the Ajax response returns and sets user, but your getit() function returned a long time ago!

You can force the Ajax call to be synchronous using the async option, like this:

  $.ajax({
    async: false,
    url: ws_url,
    type: "GET",
    success: function(data) {
        alert('user '+data.user);//shows john
        user = data.user || false;
    }
  });

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 calling getit(), and have it expect to process it's results whenever it can, perhaps by passing it's own callback function to getit() that would then be executed when getit() is done.


Ajax is asynchronous, which means that the rest of the script isn't going to sit around and wait for it to finish before moving on. As in your example, the return line is being reached before the ajax function receives a response from the server, thus the user variable is still false at that point in time.

If you want to force an ajax call to run synchronously, you can use jQuerys $.ajax method and set the async parameter to false.

$.ajax({
  url:ws_url,
  dataType:"json",
  async:false,
  success:function(data){
    alert('user '+data.user);//shows john
    user = data.user || false;
  }
});

Need Your Help

sphinx, xmlpipe2, and cassandra

ruby cassandra sphinx ruby-1.9

I start to using cassandra and I want to index my db with sphinx.

Kendo UI Treeview doesn't display date correctly

json asp.net-mvc kendo-ui

I am trying to display my json from a mvc controller to be displayed on a checkboxed kendo ui treeview. The code on the asp.net mvc view and the json sent to the view are given below