Alex
Alex

Reputation: 7688

jQuery post() return true or false

I've been searching for answers for a while, before thinking of asking here, but I just got stuck.

I've read some articles/question similar to mine, but ended following these one:

And I ended up with this:

var del_act = (function(){
    var resp;

    $.post(url+'delete/'+id, 'json')
    .done(function(data) {
        custom_alert(type.toUpperCase()+' deleted succesfully!');
        if(redirect)
            window.location.replace(url);
        resp = true;
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
        if(jqXHR['status'] == 404)
            custom_alert(type + ' not found');
        resp = false;
    });

    return {getResp: function()
    {
        console.log(resp);
        return resp;
    }};
})();

console.log(del_act.getResp());

But the problem is that both console.logs returns an undefined response. I know I could use $.ajax() with async: false, but I don't want to, so I'm trying to find a way of returning a true or a false response.

Upvotes: 0

Views: 4168

Answers (3)

axel_c
axel_c

Reputation: 6796

$.post() is asynchronous, meaning it returns immediately after the request is sent, and the code after it is executed sequentially. In this case, your console.log gets called but your request is running asynchronously, so you cannot get its return value.

The way to deal with this kind of asynchronous scenarios is to use callbacks, eg. you specify a returnCallback parameter, and you call it in the "done" callback of your $.post call.

var del_act = (function(doneCB){
    var resp;

    $.post(url+'delete/'+id, 'json')
    .done(function(data) {

        // Call CALLBACK specifying return status
        doneCB(true)
    })

The thing with asynchronous code is that it forces you to do everything in cascading callbacks, e.g. you CANNOT do:

console.log(del_act(whatever))

Because that will give you undefined, since, as explained before, the async function is still running separately. You have to think differently. In this case, you have to set up so that console.log happens after the work is done:

del_act(function() { console.log("del_act finished, status OK!"); }

Upvotes: 3

Hiren Desai
Hiren Desai

Reputation: 1091

jqXHR

it's self is and object and writing the same to console directly would give either undefined or object as output.
It seems that response coming back from the server is not valid one since it's firing fail event.
Make sure that you are returning valid JSON data.

you should have posted a link to have better view of the problem.

Upvotes: -1

James
James

Reputation: 2033

Variables cannot be transferred out of the ajax call like that.

What you should do, instead, is to call a function inside the success/fail that passes the value of true or false and then put the code inside the function to act on that true/false output

Upvotes: 1

Related Questions