Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to wait for ajax to return (I don't want to use the success handler.) [duplicate]

Possible Duplicate:
How can I get jQuery to perform a synchronous, rather than asynchronous, AJAX request?
how to wait for an ajax call to return

Hear me out. I completely understand this code segment.

$.getJSON(someURL, function(data){
    //do something with my data
})
.success(function () {
    //Call what you want on success
})

This seems fine if I just need to take one action that is pretty static. However, what if I want to be less restricted, for instance this

function my_func(){
    $.getJSON(someURL, function(data){
        //do something with my data... like modify an array or the dom
    })
}

Now the driver

my_func();
//Now I want to call a function that relies on the data that my_func brought into the script.

Is there something wrong with the way I'm coding my script if I want to do it like this? Or am I just missing some awesome built in method?

like image 942
Jake Avatar asked Mar 10 '12 14:03

Jake


People also ask

How can ajax execution be stopped after success?

// Perform a simple Ajax request var req = $. ajax({ type: "GET", url: "/user/list/", success: function(data) { // Do something with the data... // Then remove the request. req = null; } }); // Wait for 5 seconds setTimeout(function(){ // If the request is still running, abort it. if ( req ) req.

Does ajax wait for response?

ajax() function with the default settings, any JavaScript code after this AJAX request will be executed without waiting for a response. In most cases, this is the desired behavior, but there are some situations where you will want to prevent further execution until there has been a response to the AJAX call.

How do I return data after ajax call success?

You can store your promise, you can pass it around, you can use it as an argument in function calls and you can return it from functions, but when you finally want to use your data that is returned by the AJAX call, you have to do it like this: promise. success(function (data) { alert(data); });

Does ajax need a success function?

The ajaxSuccess event is only called if the request is successful. It is essentially a type function that's called when a request proceeds. The function takes three parameters, namely: The data returned from the server, formatted according to the dataType parameter, or the dataFilter callback function.


2 Answers

I see two possible jQuery-ish ways there.

The first would be to use another callback that can be passed to my_func:

function my_func(callback) {
    $.getJSON(someUrl, function(data) {
        // ...do stuff ...
        if ($.isFunction(callback)) { callback(data); }
    });
}

my_func(function(data) {
    // ..do more stuff..
});

The second way would be to create a custom event that gets triggered inside my_func and can be listened to from the outside:

function my_func() {
    $.getJSON(someUrl, function(data) {
        $(document).triggerHandler('my_func:data-received', [data]);
    });
}

$(document).on('my_func:data-received', function(event, data) {
    // ...do stuff...
});

my_func();

I strongly recommend using async: false only if it is absolutely necessary.


Just another (very neat) way to deal with this is the jQuery.Deferred object:

function my_func() {
    var d = new $.Deferred();
    $.getJSON(someUrl, function(data) {
        d.resolve(data);
    });
    return d;
}

my_func().done(function(data) {
    // ...do stuff...
});

Your function returns an object that allows to register callbacks. Within the function you then just need to make sure to call resolve to invoke all registered done callback handlers.

like image 166
Niko Avatar answered Oct 24 '22 22:10

Niko


Then there's the XHR object:

var jqXHR = $.getJSON(someURL);

You can access it anywhere after it is defined:

jqXHR.always(function() {
    alert('JSON IS COMLETE');
});

jqXHR.done(function(data) {
    //do something with the returned data if success!
});

jqXHR.fail(function(jqXHR, textStatus) {
    alert('JSON FAILED : '+textStatus);
});

FIDDLE

You could even do something like this:

$("#button").on('click', Myfunc);

function Myfunc() {
    var jqXHR = runAjax();
        jqXHR.done(function(data) {
            alert($.parseJSON(data));
            $("#result").html('JSON IS DONE');
        });
}

function runAjax() {
    return $.getJSON(someURL);
}

FIDDLE

like image 38
adeneo Avatar answered Oct 24 '22 22:10

adeneo