0

I'm setting up all my variables before I'll start to call other functions. For that I need gridData from the database. I use AJAX to pull that data and use GET variables to use for the database query.

function loadPage() {
    console.log("loading Page");

    //prepare Data
    let _GET = pullGET();
    let gridID = _GET.get("gridID");
    let gridData = pullGridData(gridID);

    console.log(gridData);
    //start rending the Page
}

When I try to console log the GridData, it gives me "undefined".

function pullGridData(gridID) {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {

            let DATA = JSON.parse(this.responseText);
            console.log(DATA[0]);
            return DATA[0];
        }
    };
    xhttp.open("POST", "action/PullGridData.php", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    var header = "gridID=" + gridID;
    //console.log(header);
    xhttp.send(header);
}

It is weird that when I console log the "DATA" that I'm trying to pass along, I get what I expect.

I am aware that jQuery might have some good solution, but I'm trying to implement this with just pure JS so I can learn on.

Dark
  • 3
  • 1
  • 1
    Because it is asynchronous, you can not return. The function is done running before the onreadystatechange is called. – epascarello Jun 01 '22 at 17:01
  • 1
    You are dealing with asynchronous HTTP requests. The `onreadystatechange` callback executes after the asynchronous request completes. The request isn't complete when you `console.log(gridData)`. Also, `pullGridData` doesn't even return anything, so it is expected to return `undefined`. – h0r53 Jun 01 '22 at 17:01

0 Answers0