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.