-2

I have this function :

    function getDatas() {
    var xmlhttp = new XMLHttpRequest();
    var response = null;
    xmlhttp.open("POST", "getdatas.php", true);
    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState === 4) {
            if(xmlhttp.status === 200) {
                response = xmlhttp.responseText;
                return response;
            }
            else {return xmlhttp.statusText;}
        }
    };
    xmlhttp.send(null);
}

The response is in a JSON format and correctly filled. How to return the response for another use like :

var datas = getDatas();

UPDATE : After the callback I have this :

function AppViewModel() {
    var _self = this;
    getDatas(function(error, result) {
        if(error) {
            alert(error);
        } else {
            _self.datas = result;
            console.log(_self.datas);
        }
    });
    console.log(_self.datas);
}

The first console.log(_self.datas); works well but the second is undefined.

Dipiks
  • 3,818
  • 2
  • 23
  • 39

1 Answers1

0

AJAX is asynchronous, so you don't return any values from such functions, you use callbacks and use the value inside the callback:

function getDatas(callback) {
    var xmlhttp = new XMLHttpRequest();
    var response = null;
    xmlhttp.open("POST", "getdatas.php", true);
    xmlhttp.onreadystatechange = function() {
        if(xmlhttp.readyState === 4) {
            if(xmlhttp.status === 200) {
                response = xmlhttp.responseText;
                callback(null, response);
            }
            else {
               callback(xmlhttp.statusText, null);
            }
        }
    };
    xmlhttp.send(null);
}

and then when you call the getDatas function you provide a callback which will be invoked when the AJAX request finishes and it will either contain the result or an error:

getDatas(function(error, result) {
    if (error) {
        alert('An error occurred while retrieving data: ' + error);
    } else {
        // Use the result variable here
    }
});
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks for the help ! I updated my question, can you help me one more time ? :) – Dipiks Apr 26 '15 at 17:09
  • 1
    You can capture `this` just before calling the `getDatas` function: `var _self = this;` and then inside the callback use `_self.datas = result;`. – Darin Dimitrov Apr 26 '15 at 17:15