Return in each getJSON - Jquery

3

I would like to know the following how do I give return in a function created by me in a situation below. For always returns undefined object, but when I give an alert it returns the normal object.

  function jjson(url){
            var result;
            $.getJSON( url, function(data) {
                alert(data)
                result = data;
            });

            return result;
        }

ATT

    
asked by anonymous 30.04.2015 / 21:43

1 answer

2

This function will always give return undefined because AJAX is asynchronous.

You need to use a callback to do what you need when the server's response arrives. You can use it like this:

function jjson(url, callback){
        $.getJSON( url, callback);
 }

and then call the function by passing to the callback what you want to do:

jjson('google.com', function(result){
    alert(result);
});

In practice this can be simplified if you put what you want to do directly in getJSON ...

$.getJSON(url, function(data) {
    gerarGrafico(data); //por exemplo
});

Well, this code is only run when the server data has arrived.

    
30.04.2015 / 21:47