makeee
makeee

Reputation: 2805

How can I return AJAX response text?

For the sake of better organized code, instead of putting a callback function within my req.onreadystatechange handler, I'd like to simply return the data.

In the following javascript, the "raw_data" var 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 to not call parse_data() until the req.onreadystatechange within the ajax_fetch_data() returns data?

I don't like having the parse_data() call nested as a callback within ajax_fetch_data().

Upvotes: 2

Views: 1657

Answers (2)

user181548
user181548

Reputation:

The A in Ajax means "asynchronous". If your call is asynchronous, it is not possible to use a return value like that. You have to wait for the event with a callback. 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 the false on the second line specifies the synchronous nature (default value of the third argument is true).

There is more at Mozilla Developer Center.

Upvotes: 1

rocketmonkeys
rocketmonkeys

Reputation: 5743

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

Usually it's 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 essentially you have two threads: the main program where you "start" a request, and the callback function that gets called when the request is complete. This still ignores the details.

If you want SJAX (a bad abbreviation for syncronous javascript & xml), then you could 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, this performs a busy-wait (ie. your browser is stuck/locked-up until the data comes in... could be a few ms, could be a minute, who knows). So this should only be used when necessary. If you just want to get 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.

Upvotes: 1

Related Questions