How can I return the AJAX response text?

For better ordered code, instead of putting a callback function in my req.onreadystatechange handler, I would like to just return the data.

In the following javascript var1 raw_data is undefined because parse_data () function is called before the ajax response.

function dostuff(){
   var raw_data = ajax_fetch_data();
   var parsed_data = parse_data(raw_data);
}

      

Is it possible not to call parse_data () until req.onreadystatechange inside ajax_fetch_data () returns data?

I don't like it when the parse_data () call is nested as a callback in ajax_fetch_data ().

+2


source to share


2 answers


A in Ajax stands for asynchronous. If your call is asynchronous, there is no way to use the return value. You have to wait for the callback event. However, you can send a synchronous request like this:

var req = new XMLHttpRequest();  
req.open('GET', 'http://www.example.org/', false);
req.send(null);  
if(req.status == 200)  
    return req.responseText;  

      



where false

the second line indicates the synchronous character (the default of the third argument true

).

To the Mozilla Developer Center .

+1


source


This code is too vague: var raw_data = ajax_fetch_data ();

It usually looks like this:

// url = ...
// data = ...
create_ajax_request(url, data, callback);
// This will continue to execute like normal
// ...
// ...
// ...

// Now, in a differnt part of the code:
function callback() {
    // Sometime later, when AJAX returns data, this is called.
}

      

So, you have two threads: the main program, where you "start" the request, and the callback function, which is called when the request is complete. It still ignores the details.

If you want SJAX (bad shorthand for synchronous javascript and xml), then you can use something like jQuery:



var result = null;
$.ajax({
    aync: false,
    data: data,
    url: url,
    success: function(data) {
        result = data;
    }
});
// result is populated before $.ajax() moves on, so you can use it right after
console.log('result: ' + result);

      

However, it does wait-wait (i.e. your browser gets stuck / blocked until data arrives ... maybe a few ms, maybe a minute, who knows). Therefore, it should only be used when needed. If you just want to get the data and then process it, use callbacks.

// Call this to start a request
function startRequest() {
    data = ...
    create_ajax_request(url, data, continueRequest);
}

// This is called once we have the data
function continueRequest(data) {
    alert(data);
}

      

This is more typical of AJAX programs.

+1


source







All Articles