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);
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
dvariable 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
doneevent, 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:
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.