blc
blc

Reputation: 161

JS object returned but responseText doesnt work

So I am posting a call to a method that just returns a string and my post request returns an object with a string in the responseText field, but the d.responseText returns "undefined." Anyone know why? I thought it was because it was AJAX but why is does the var d have the correct value?

var d = $.post("/home/status_update", function(data) {return data});
console.log(d);
console.log(d.responseText);

Upvotes: 1

Views: 1972

Answers (2)

Cranio
Cranio

Reputation: 9837

It's one of the far most common errors I'm finding here on AJAX requests: many people don't realize that AJAX is *A*synchronous, you can't expect that your d variable gets valued because the code continues its execution regardless of the completion of the AJAX request.

You can use the retrieved value only when the request-response roundtrip has been completed.

What you have to do is to actually use the returned value inside the function(data), because you are guaranteed that it will be executed only after the value is actually retrieved.

The other user obtains the same thing by binding the done event, that is fired upon the completion of the AJAX request/response. It's the same thing coded in a slight different manner. The shorthand is:

var d = $.post("/home/status_update", function(data) {console.log(data);});

Bear in mind that, as a general application architecture, with AJAX requests you cannot expect to use a single function, you will define functions that will manupulate your response upon every AJAX completion. Try to think your application in a more "fragmented" way.

Upvotes: 4

Kevin B
Kevin B

Reputation: 95031

$.post returns a promise object, try using it.

var d = $.post("/home/status_update");
d.done(function(data) {
    console.log(data);
});

Upvotes: 5

Related Questions