Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning values from the event onreadystatechange in AJAX [duplicate]

I am trying to assign a value to the variable val in the code below:

var cmdValue = "/cmd/fetch?x=";
var val;
var returned_data;

function what(){
    val = update('#TAG#');
}


function update(tag) {
    var req1 = newXMLHttpRequest();
    req1.open("GET",cmdValue + tag, true);
    req1.send("");

    return req1.onreadystatechange= function () {
        if (req1.readyState == 4 && req1.status == 200) {
            returned_data = req1.responseText;
            return returned_data;
        }else{

        }
    };
}

I was tracking the variables in Firebug and it turns out that val gets assigned the function. Is there a way to get the code to run through and then assign the value to the variable val?

like image 234
Superios Avatar asked Dec 11 '22 10:12

Superios


1 Answers

In asynchronous programming you do not return data because you don't know when that data is going to become available - it's asynchronous.

The way to do asynchronous programming is using events and/or callbacks.

Example:

var cmdValue = "/cmd/fetch?x=";
var val;
var returned_data;
var performSomeAction = function(returned_data) {
    val = returned_data;
}

function what(){
    update('#TAG#', performSomeAction);
}


function update(tag, callback) {
    var req1 = new XMLHttpRequest();
    req1.open("GET", cmdValue + tag, true);
    req1.send("");

    req1.onreadystatechange= function () {
        if (req1.readyState == 4 && req1.status == 200) {
            returned_data = req1.responseText;
            //fire your callback function
            callback.apply(this,[returned_data]);
        } else {

        }
    };
}

This question is one of the most commonly asked questions on SO, at least when it comes to the javascript tag - please search for similar questions before asking your own.

like image 141
Adam Avatar answered Mar 30 '23 01:03

Adam