Cham
Cham

Reputation: 131

Not getting the array from Node.js to AJAX

Hi it seems based on my code that I am not reaching or responding the array from Node.js to AJAX no other errors or what not but I can not seem to figure out what is wrong with my code see below. Thank you in advance for your help!

AJAX code below:

function update() {
let rq = new XMLHttpRequest();
    rq.onreadystatechange = function() {
        if(rq.readyState == 4) {
        var arr = JSON.parse(rq.responseText);
        for(var i = 0; i < arr.length; i++) {
        document.getElementById("message").innerHTML += "<p>" + arr[i] + "</p>";
        }
    }
    rq.open("GET", "/messages", true);
    rq.send();
  }
}

Node.js code to handle GET:

if(req.method == "GET") {
  req.on('data', function(data) {
    console.log("You are reching GET-DATA");
  });
  req.on('end', function() {
    console.log("You are reching GET-END");
    res.writeHead(200, { "Content-Type" : "application/json" })
    console.log(JSON.stringify(arr))
    var toString = JSON.stringify(arr);
    res.end(JSON.stringify(arr));
  });
}

enter image description here

I am reaching console.log(req.readystate) and it ouputs "1", alert("Your program reached rq.onreadystatechange"); and alert("Your program reached rq.onreadystatechange = 4"); and then after awhile the response will now be received and I see error on the console.

enter image description here

Upvotes: 0

Views: 61

Answers (1)

trincot
trincot

Reputation: 351128

The ajax code has the open and send within the onreadystatechange callback. You need to move that out of there:

function update() {
    console.log('update called');
    let rq = new XMLHttpRequest();
    rq.onreadystatechange = function() {
        console.log('readyState: ' + rq.readyState);
        if(rq.readyState == 4) {
            console.log('responseText: ' + rq.responseText);
            var arr = JSON.parse(rq.responseText);
            for(var i = 0; i < arr.length; i++) {
                document.getElementById("message").innerHTML += "<p>" + arr[i] + "</p>";
            }
        }
    };
    // moved out of above function
    rq.open("GET", "/messages", true);
    rq.send();
}

By adding some console.log calls you can also better follow what is (not) happening.

Upvotes: 3

Related Questions