Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

wait for a jquery ajax callback from calling function

I have reviewed a lot of answers to this type of question and now I am confused as to the best way. Given the latest jquery, I am wanting to

  1. Call an ajax function
  2. do ajax processing (success or error) // works fine
  3. on success or error return the status to the calling function for further processing

in the calling function (doAjax), how do I wait for a callback then complete the processing for success or error (in this case its on success clear a form, on error keep it as is)

Thx for any advice,

Art [EDIT] There was a typo as you guys spotted, call should have been doAnAjax not doAjax

$(function () {
    doAnAjax(Url, data, function (myRtn) {
        if (myRtn == "success") {
            resetForm($('#myForm'));
            resetForm($('form[name=addChlGrp]'));
        } else {
            $('.rtnMsg').html("Opps! Ajax Error");
        }
    });
});

function doAnAjax(newUrl, data) {
    $.ajax({
        url: newUrl,
        async: true,
        dataType: 'html',
        beforeSend: function () {
            $('.rtnMsg').html("<img src=_cssStyleImg_-A-loading.gif>");
        },
        type: "GET",
        data: data,
        cache: false,
        success: function (data, textStatus, xhr) {
            $('.rtnMsg').html(data);
            myRtnA = "Success"
            return myRtnA;
        },
        error: function (xhr, textStatus, errorThrown) {
            $('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
            myRtnA = "Error"
            return myRtnA;
        }
    });
}
like image 527
art vanderlay Avatar asked Jul 20 '12 09:07

art vanderlay


People also ask

Can you await an ajax call?

I recently remembered this and I thought to myself: Since async/await is just Promise's under the hood, I wonder if I can use async/await with jQuery's $. ajax(). Turns out, you can!

Is there any way to wait for ajax response and halt execution?

Cut and paste whatever code you need to execute in the callback function passed to success . Some good answer is already provided.

How do I return a response from ajax?

The A in Ajax stands for asynchronous. That means sending the request (or rather receiving the response) is taken out of the normal execution flow. In your example, $. ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.


2 Answers

You've got to use a callback function. Try this below:

$(function() {

   // I think doAjax should doAnAjax()
   // here you're passing callback
   // but you're not using it doAnAjax()

    doAnAjax(Url, data, function(myRtn) {
        if (myRtnV == "success") {
            resetForm($('#myForm'));
            resetForm($('form[name=addChlGrp]'));
        } else {
            $('.rtnMsg').html("Opps! Ajax Error");
        }
    });
});

// pass callback as third parameter to doAnAjax()

function doAnAjax(newUrl, data, callBack) {
    $.ajax({
        url: newUrl,
        async: true,
        dataType: 'html',
        beforeSend: function() {
            $('.rtnMsg').html("<img src=_cssStyleImg_-A-loading.gif>");
        },
        type: "GET",
        data: data,
        cache: false,
        success: function(data, textStatus, xhr) {
            $('.rtnMsg').html(data);
            myRtnA = "Success"
            return callBack( myRtnA );  // return callBack() with myRtna
        },
        error: function(xhr, textStatus, errorThrown) {
            $('.rtnMsg').html("opps: " + textStatus + " : " + errorThrown);
            myRtnA = "Error"
            return callBack ( myRtnA ); // return callBack() with myRtna
        }
    });
like image 126
thecodeparadox Avatar answered Sep 28 '22 11:09

thecodeparadox


As previously mentioned, using Callbacks.

function process(url, params, successCallback, errorCallback) {
    $.ajax({
        success : successCallback,
        error : errorCallback,
        data : params,
        url : url,
        type : 'POST',
        dataType : 'json'
    });
}

process(
    'http://www.google.co.uk', 
    { 
        param1 : 'a' 
    }, 
    function(resp) { 
        alert('Success');
    },
    function() {
        alert('Uh oh');
    }
);

You can then pass any function to process and it will be called on success/error.

like image 39
Gavin Avatar answered Sep 28 '22 11:09

Gavin