0

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.

Community
  • 1
  • 1
Alex
  • 7,538
  • 23
  • 84
  • 152

3 Answers3

3

$.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!"); }
axel_c
  • 6,557
  • 2
  • 28
  • 41
  • Err yes, haven't checked the docs for a while but back in my day it was success. Whatever is cool these days, the important thing is that you get the idea about callbacks. – axel_c Feb 26 '13 at 14:05
  • the problem is that when I call `doneCB(true)` I get `undefined is not a function` – Alex Feb 26 '13 at 14:07
  • well, you have to pass doneCB as a parameter to del_act, eg. `del_act(function() {alert("i am doneCB!!!");});` – axel_c Feb 26 '13 at 14:08
  • No...you cannot call console.log to print something that will be asynchronous and expect it to work... you have to do the asynchronous work, and THEN call console.log from the asynchronous callback – axel_c Feb 26 '13 at 14:12
  • Caused by your `window.location` change - if you redirect then execution of javascript will be stopped for current page. – axel_c Feb 26 '13 at 14:56
  • axel, the `window.location ` has nothing to do with it, it was the first thing I removed when the issue ocurred. Executing a `del_act()` will issue the redirect, while `del_act;` (and it executes the post) not – Alex Feb 26 '13 at 14:58
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/25163/discussion-between-w0rldart-and-axel-c) – Alex Feb 26 '13 at 15:00
  • tried a couple of things... still nothing, this is what I'm trying now http://pastebin.com/CeskXVvX – Alex Feb 26 '13 at 15:08
1

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

James
  • 2,013
  • 3
  • 18
  • 31
  • The problem with your suggestion is that is going to get a little messy, as I have to declar a `var resp` at the very beggining of all scripts, then set a value to it and then retrieve it... that's how you thought of it, right? – Alex Feb 26 '13 at 14:29
-1
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.

Hiren Desai
  • 941
  • 1
  • 9
  • 33