1

How do I return the response from an asynchronous call? Did not helped me and will probably confuse a lot on googlers because its state what is working as not working. witch is; the_data_you_want = response and this is actually the answer.

I am working on a project that uses Ajax, Jquery, Promise, and PHP.

I fill an array with a function.

var data = validateInput2(field_id, data_type, value).then(function (response) {
        console.log("Succès !", response);  <-----------------------------
        data = response;                     Scope where data is filled
        alert('R : '+data);                 <-----------------------------
    }, function (error) {
        console.error("Échec !", error);
    });
    alert('DATA : '+data);                    <---------------------------
    if (data[0] == 'true') {                   Outside the scope where data 
        $(container[1]).addClass("pass_f");    is a pending promise object
        $(container[1]).html(data[2]);
        $(container[0]).html(data[1]);
    }
    else {
        $(container[1]).removeClass("pass_f");
        $(container[1]).addClass("err_f");
        $(container[1]).html(data[2]);
        $(container[0]).html(data[1]);
    }

Now if you take a look at the alert statement, The first one alert('R : '+data); is showing me what i am suppose to see. an array sent back from PHP. I can see the same good values in the console because of console.log("Succès !", response); but when i keep going and get to the part where the page should get updated. Witch is the alert('DATA : '+data); The data is no longer what it was. Instead I get [object Object] in the alert box. And in the console I get

Promise {[[PromiseStatus]]: "pending", [[PromiseValue]]: undefined}

It seems like the array contained in result is only there inside;

  {
        console.log("Succès !", response);
        data = response;                  
        alert('R : '+data);
    }

So I know that my Promise is working because my page is waiting for the object with the status pending and that I no longer have the data undefined error.

Community
  • 1
  • 1
MadeInDreams
  • 1,991
  • 5
  • 33
  • 64
  • 1
    The variable `data` is a local variable and you are trying to access it outside of its scope – Akshay Jan 19 '16 at 08:06
  • so if i move all my code in there it should work? – MadeInDreams Jan 19 '16 at 08:07
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Jaromanda X Jan 19 '16 at 08:07
  • Why are you overwriting `var data` with `response`? – Thomas Jan 19 '16 at 08:07
  • `console.log("Succès !", response)` will use the browser's special display of both parameters: `response` as an object gets rendered into the nice drop-downy tabular thing. Replace the comma with a plus, and you get something very different: `'DATA : '+data` will invoke `data.toString()` in order to be able to perform the concatenation, and the default `toString` of an object is `[object Object]`. `console.log` then outputs the string it is given: `"R : [object Object]". Your `data` variable is at that moment still correct. The out-of-scope issue mentioned in the accepted answer is unrelated. – Amadan Jan 19 '16 at 08:20
  • That is to say, it is the true source of your problem; but the misunderstanding about `toString` and two different ways to use `console.log` tripped you up and led you down a garden path. – Amadan Jan 19 '16 at 08:21
  • @Amadan The out of scope was exactly what was wrong with it. And the console did not led to a garden of path but told me what i needed to know. Witch was that my promise was working and the value outside of the scope is pending! – MadeInDreams Jan 19 '16 at 09:52

2 Answers2

3
var data = validateInput2(field_id, data_type, value).then(function (response) {
        console.log("Succès !", response);
        data = response;
        if (data[0] == 'true') {
            $(container[1]).addClass("pass_f");
            $(container[1]).html(data[2]);
            $(container[0]).html(data[1]);
        }
        else {
            $(container[1]).removeClass("pass_f");
            $(container[1]).addClass("err_f");
            $(container[1]).html(data[2]);
            $(container[0]).html(data[1]);
        }
    }, function (error) {
        console.error("Échec !", error);
    });
    alert('DATA : '+data);

it's because you are working with data, and data in that moment is promise, so do it like this

Darkves
  • 352
  • 2
  • 10
  • YESSSSS i just did exactly that came back here and saw that you came up with this same exact code. Thank you so much after 6 hours i finally get it! Thank god i dont need to reinvent the wheel – MadeInDreams Jan 19 '16 at 08:12
1

I have unwound your callback function for clarity, for you to spot the error:

var success_func = function (response) {
    console.log("Succès !", response);
    data = response;
    alert('R : '+data);
};
var error_func = function (error) {
    console.error("Échec !", error);
};
var data = validateInput2(field_id, data_type, value).then(success_func, error_func);
alert('DATA : '+data);
if (data[0] == 'true') {
    // ...
} else {
    // ...
}

success_func is called some time in the future, when your ajax call has completed. So when validateInput2 returns, it's likely that success_func is not yet even called. then returns a Promise object, not the data from server you would expect.

Right way to handle the situation is to put all your data handling inside success_func:

validateInput2(field_id, data_type, value).then(function (response) {
    console.log("Succès !", response);
    data = response;
    if (data[0] == 'true') {
        $(container[1]).addClass("pass_f");
        $(container[1]).html(data[2]);
        $(container[0]).html(data[1]);
    }
    else {
        $(container[1]).removeClass("pass_f");
        $(container[1]).addClass("err_f");
        $(container[1]).html(data[2]);
        $(container[0]).html(data[1]);
    }
}, function (error) {
    console.error("Échec !", error);
});
Joe
  • 1,656
  • 11
  • 10
  • Thank you. Indeed that fixed it. i spent a lot of time on it since promise was new to me. But at least now i understand it. And its pretty awesome to be able to do that! – MadeInDreams Jan 19 '16 at 08:27