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

ArtOfCode
  • 5,702
  • 5
  • 37
  • 56
user3483449
  • 11
  • 1
  • 1
  • 6

3 Answers3

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.

Hubert Grzeskowiak
  • 15,137
  • 5
  • 57
  • 74
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();
Rajesh
  • 24,354
  • 5
  • 48
  • 79
cemsina güzel
  • 390
  • 4
  • 14
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();
    });
Erick Jimenez
  • 368
  • 2
  • 13