0

I have gone through many topics on stack overflow for jquery asynchronous AJAX requests. Here is my code.

funciton ajaxCall(path, method, params, obj, alerter) {
var resp = '';
$.ajax({
    url: path,
    type: method,
    data: params,
    async: false,
    beforeSend: function() {
        $('.black_overlay').show();
    },
    success: function(data){
        console.log(data);
        resp = callbackFunction(data, obj);
        if(alerter==0){
            if(obj==null) {
                resp=data;
            } else {
                obj.innerHTML=data;
            }
        } else {
            alert(data);
        }
    },
    error : function(error) {
        console.log(error);
    },
    complete: function() {
        removeOverlay();
    },
    dataType: "html"
});

return resp;
}

The problem is, when I use asyn is false, then I get the proper value of resp. But beforeSend doesn't work.

In case, I put async is true, then its beforeSend works properly, but the resp value will not return properly, Its always blank.

Is there any way to solve both problems? I would get beforeSend function and resp value both.

Thanks

4

3 Answers 3

1

Use async:false and run the function you assigned to beforeSend manually before the $.ajax call:

var resp = '';
$('.black_overlay').show();
$.ajax({
    ...

Either that or learn how to use callback functions with asynchronous tasks. There are many nice tutorials on the web.

0
  1. Take the resp variable out from the function
  2. Create one extra function respHasChanged()
  3. when you get the data successfully, use the code resp = data;respHasChanged();
0

You can restructure on this way, (why no use it in async way?)

function ajaxCall(path, method, params) {
    return $.ajax({
        url: path,
        type: method,
        data: params,
        beforeSend: function() {
            $('.black_overlay').show();
        },
        dataType: "html"
    });
}

Call in your javascript file

ajaxCall(YOUR_PATH, YOUR_METHOD, YOUR_PARAMS)
    .done(function(data) {
        console.log(data);

        // DO WHAT YOU WANT TO DO

        if (alerter == 0 && obj !== null) {
            obj.innerHTML = data;
        } else {
            alert(data);
        }
    }).fail(function(error) {
        console.log(error);
    }).always(function() {
        removeOverlay();
    });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.