Return in each getJSON - Jquery

Asked

Viewed 652 times

3

I would like to know the following how do I give Return in a function created by me, in a situation below. Because it always returns Undefined the 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

1 answer

2


This function will always give Return Undefined because AJAX is asynchronous.

You have to wear a callback to do what you need to do when the server response comes in. 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 into getJSON...

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

'Cause then that code will only run when the server data has arrived.

  • 1

    Thank you... ATT

  • So it is impossible to use the data outside of it, put in a variable or give a return to be used?

  • @Exact Winefile. Any JSON code that has to be called/used within the callback of the getJSON. You can for example call a function, passing JSON as argument. So you run code with this new data coming from JSON.

  • @Sergio Since it is not possible to do this, I do so <script>var theme = <?= json_encode(new \Skreth\System\Theme()); ?>;</script> can be considered gambiarra?

  • @Viníciusfile works fine if the data is static. If you need to fetch fresh data without reloading the page then getJSON is the best. Failed to implement with getJSON?

  • @Sergio are static data, about the theme’s default colors, type: Secondary: "gray600" Featured: "cyan". Then I would like to access them more or less like this: theme.Secondary. That way I can, but I don’t know if it’s 100% right

  • 1

    @Viniciuuslima ok, then putting in a var sounds good to me

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.