Lee Loftiss
Lee Loftiss

Reputation: 3195

jquery handle ajax response outside of ajax object

I am working with jQuery and I need to handle the data gathered during an AJAX call outside of the AJAX object:

function getData(yt_url) {
    $.ajax({
        type: "GET",
        url: yt_url,
        dataType: "jsonp",
        success: function(response) {
            //   Return response here //

        },
        error: function(request, status, error) {
            alert(status);
        }
    });
}

I would like to call the function getData and receive the response object in the AJAX success function.

I've tried adding some returns and then of course I realized it was an object.

Upvotes: 6

Views: 19120

Answers (6)

goulashsoup
goulashsoup

Reputation: 3076

You can also make the get-function asynchronous and use await to wait for the response:

async function getData(yt_url, callback) {
    return await $.ajax({
        type: "GET",
        url: yt_url,
        dataType: "jsonp",
        success: callback,
        error: function(request, status, error) {
            alert(status);
        }
    });
}​

getData().then(response => console.log(response)); // `getData` will return a promise

// But you can use await for `getData()` in another `async function`:
async function useData() {
    const data = await getData();
    console.log(data);
}

Upvotes: 0

Tushar Kshirsagar
Tushar Kshirsagar

Reputation: 303

I don't know this fits for any of you, but what i did in my case is, I stored the response data in "localSotrage" of browser and later used that "localSotrage" data in other usual javascript function !! Give it a try if it fulfills your purpose !!

Also let me know, if this approach has some negative impacts !!

Upvotes: 1

Ioannis Karadimas
Ioannis Karadimas

Reputation: 7896

Since AJAX is asynchronous, you should restructure your code to receive the data in a callback function. Whenever the request is finished, you then can continue with whatever you wanted to do with the data. An example:

$.ajax {
    type: "GET",
    url: url,
    dataType:"jsonp",
    success: success,
    error: error
};

function success(data) {
    // continue your work here.
}

function error(request, status, error) {
    // handle any errors here.
}

I would not recommend using async: false, since it freezes the browser until it finishes executing your request, while in general you might like it to remain responsive while it processes your code.

Upvotes: 1

Danilo Radenovic
Danilo Radenovic

Reputation: 1029

You can try something like this - add a global variable that will store the result of the ajax call, for example

var ajaxResult = null;

set ajax's async property to false and then write something like this:

var ajaxResult = null;

function getData(yt_url){
$.ajax
        ({
            type: "GET",
                        url: yt_url,
                        dataType:"jsonp",
                        async: false,
                        success: function(response){
                            ajaxResult = response; 

                        },error:function (request, status, error)           
});

}

getData(yt_url); // call the function to try to get the result if(ajaxResult != null){ // if we got some result during the ajax call

    // do something with the result

}

Upvotes: 1

Blender
Blender

Reputation: 298136

AJAX is asynchronous, which basically means that it does not block the execution of the script (which is good, as your website does not freeze while things load).

returning a value like you're doing is synchronous, which is incompatible with AJAX.

One solution would be to pass a callback function into getData that gets called when the AJAX request finishes:

function getData(yt_url, callback) {
    $.ajax({
        type: "GET",
        url: yt_url,
        dataType: "jsonp",
        success: callback,
        error: function(request, status, error) {
            alert(status);
        }
    });
}​

And then you could use it like this:

getData('http://www.example.com/', function(response) {
    alert('The response was: ' + response);
});

Upvotes: 9

Fabrizio Fortino
Fabrizio Fortino

Reputation: 1606

jquery ajax is async by default. Use async : false to disable it.

    function getData(yt_url){
        var data;
        $.ajax
        ({
            type: "GET",
                        async: false,
                        url: yt_url,
                        dataType:"jsonp",success: function(response){
                            //   Return response here //
                            // init data variable
                        },error:function (request, status, error) {alert(status);}
                    });
         return data;
   }

Upvotes: 0

Related Questions