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");

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!