September 15, 2013
Can't get responseText from $.post
Andrey Yasinishyn’s Question:
I need to get a string from the server using jquery $.post, the issue is that I can’t get the responseText from it.
So if I run
role = $.post('user_helper/return_current_role', {id: 3}, null, "json").responseText;
console.log(role);
I get undefined
If I try
role = $.post('user_helper/return_current_role', {id: 3}, null, "json");
console.log(role);
I get an object Object { readyState=1, getResponseHeader=function(), getAllResponseHeaders=function(), more...}
, where responceText is, for example, teacher
.
Here is this response, copied from firebug:
readyState
4
responseText
"teacher"
status
200
statusText
"OK "
As it’s asynchronous, and has a callback function, how about:
$.post('user_helper/return_current_role', {id: 3}, function(result) {
var role = result;
console.log(role);
}).fail(function(a,b,c) {
console.log(a);
console.log(b);
console.log(c);
});
You can not use the result of an ajax call, until it’s returned from the server.
It’s just how asynchronous calls work!
EDIT:
chained on a fail method, see if that tells you anything ?
You can do it this way too:
$.post('user_helper/return_current_role', {id: 3}, function(data) {
var role = data;
// Now Do what you need
}, "json");