0

I've got two functions in Javascript. One gets JSON data from a php file.

{"company_name":"","job_title":"Superhero","unix_time_convert":"Posted 06th of September '18","link":"2"}

The javascript function to return the JSON is this:

function assignJsonData() {
 var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = (this.response);
            return data;
            //alert( data );
       }
    };   
    xmlhttp.open("GET", 'test_echo.php?row=1', true);
    xmlhttp.send();      
}

Notice that alert( data ); will return the JSON data in a box.

But when I assign the function to a variable elsewhere like so, it returns undefined.

window.onload = function () {
    var data = assignJsonData();
    alert(data);

}

What am I missing here?

Sorry to ask, I've been on this for hours...

Thanks

Andy

daedsidog
  • 1,732
  • 2
  • 17
  • 36
  • This is due to the fact that you don't return anything in *assignJsonData*. You return in in the anonymous function assigned to `xmlhttp.onreadystatechange`, but that's another function. – 3limin4t0r Dec 04 '18 at 10:39

4 Answers4

1

You should use callBack to retrieve data from ajax request , and get data when ajax request is finieshed , your could should look like :

function assignJsonData(callback) {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            callback(this.response);
       }
    };   
    xmlhttp.open("GET", 'test_echo.php?row=1', true);
    xmlhttp.send();      
}
window.onload = function () {
    assignJsonData(function(data){
        alert(data);
    });
}
SayJeyHi
  • 1,559
  • 4
  • 19
  • 39
  • Although this answer works, we're currently in 2018. Using callbacks introduces [callback hell](https://stackoverflow.com/questions/25098066/what-is-callback-hell-and-how-and-why-rx-solves-it) into your program and is from the ~ 2013 era. I recommend working with [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises), or the somewhat new [`async`/`await`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). – 3limin4t0r Dec 04 '18 at 12:34
  • @JohanWentholt actually , yeah you are right, but based on user code and asked question , I think we should introduce the fastest and the most understandable way of solving the problem. – SayJeyHi Dec 04 '18 at 14:14
  • I can somewhat agree with that. I'd definitely not change the answer base after it's accepted as an answer. However I believe my comment is necessary to point possible future readers in the correct direction if they want to solve the issue in a cleaner way. – 3limin4t0r Dec 04 '18 at 15:00
0

XMLHttpRequest is asynchronous. You need to either use a callback or a Promise.

function assignJsonData(callback) {
 var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            var data = this.response
            callback(data)
       }
    };   
    xmlhttp.open("GET", 'test_echo.php?row=1', true);
    xmlhttp.send();      
}

window.onload = function () {
    assignJsonData(function(data) {
      alert(data)
    });
}
3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
Errorname
  • 2,228
  • 13
  • 23
0

As Jafar pointed, you should use a callback!

If you want to check the order the things is executed, run the code bellow.

var returnData = "";

function assignJsonData() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        console.log(this.readyState, this.status);
        if (this.readyState == 4 && this.status == 200) {
            returnData = this.response;
            console.log('enter');
            //console.log(this.response);
            //return data;
            //alert( data );
       }
    };   
    xmlhttp.open("GET", 'https://jsonplaceholder.typicode.com/todos/1', true);
    xmlhttp.send();      
}

assignJsonData();
console.log("returnData: " + returnData);
Marcus Sabino
  • 340
  • 1
  • 2
  • 9
-1

You need to use Promise. Check - How do I promisify native XHR?

You don't have the data in alert, because the response is not ready I guess.

flash
  • 32
  • 4