Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I not return responseText from an Ajax function? [duplicate]

Here is part of my Ajax function. For some reason that I cannot figure out, I am able to alert() responseText but not able to return responseText. Can anybody help? I need that value to be used in another function.

http.onreadystatechange = function(){
    if( http.readyState == 4 && http.status == 200 ){
        return http.responseText;
    }
}
like image 702
Nathan Wehr Avatar asked Sep 17 '10 02:09

Nathan Wehr


People also ask

How do I get responseText in ajax?

Request(postUrl, { method: 'post', postBody: postData, contentType: 'application/x-www-form-urlencoded', onComplete: function(transport){ if (200 == transport. status) { result = transport. responseText; callback(result); } } }); } somefunction(function(result){ alert(result); });

Does ajax return anything?

ajax returns immediately and the next statement, return result; , is executed before the function you passed as success callback was even called.

What is jqXHR in ajax?

The jqXHR Object. The jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() as of jQuery 1.5 is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method.


1 Answers

You will not be able to handle the return value that you are returning from your asynchronous callback. You should handle the responseText within the callback directly, or call a helper function to handle the response:

http.onreadystatechange = function () {
    if (http.readyState == 4 && http.status == 200) {
        handleResponse(http.responseText);
    }
}

function handleResponse (response) {
    alert(response);
}
like image 69
Daniel Vassallo Avatar answered Sep 21 '22 06:09

Daniel Vassallo