0

I have a really simple ajax call that is fetching from a php file called functions.php and for our purposes, functions.php is echoing "this worked!". Here is my really simple ajax call code:

const ajax = new XMLHttpRequest();
const url = "/layout-1/functions.php";
ajax.open("GET", url);
ajax.onload = handleAjax(ajax);
ajax.send()
const response = ajax.response;
console.log(ajax);
console.log(response);

And here is the handleAjax() function (although not really applicable):

function handleAjax(xh) {
    "use strict";
    if (xh.readyState === 4) {
        switch (xh.status) {
        case 401:
            console.log("You are unauthroized to access this");
            break;
        case 403:
            console.log("This is a forbidden asset");
            break;
        case 404:
            console.log("Can't find the asset");
            break;
        case 500:
            console.log("Server failure");
            break;
        }
    }
}

After the above ajax call, I'm console.logging two things: the ajax object I created and the attribute response on that object. In the log of the object, I can see the text "this worked!", but in the log of the variable response, I am getting nothing, it is just blank. I have also tried logging responseText and the same thing happens, just a blank line in the console.log.
Why is the response present in the object, but when I try to access the response directly, it is blank?

EDIT:

I don't see how that question applies to mine though, because I'm not getting undefined in my response text, what is happening is the response is returning an empty string, but the correct response lives in the ajax object. Maybe I missed something in the linked question, but I don't think I did.

Adam McGurk
  • 186
  • 1
  • 19
  • 54
  • We think you missed something. Read it again and start realizing which calls here are actually async. – Neil Lunn Nov 17 '17 at 02:27
  • The fact that in your case you get an empty string but in the dup the result is undefined relates to the particular implementation. *The cause is the same.* You need to understand what asynchronous means. (Which is what the dup explains.) You also need to understand that `console.log(ajax)` links to a *live* object, but `response` is the static value of `ajax.response` **at the time it was assigned**.This last sentence is *not* explained in the dup and is what you "missed". – robinCTS Nov 17 '17 at 08:22

0 Answers0