JavaScript AJAX Basics (retiring) Programming AJAX Parsing JSON Data

responseText console.log is empty

I am trying the same thing as Dave did in video but I am unable to get console.log to print something in console

const xhr = new XMLHttpRequest();
xhr.readyState = function(){
    if(xhr.readyState === 4){
        console.log(xhr.responseText)
    }
}
xhr.open('GET','data/task.json');
xhr.send();

and task.json is

{
    "jobs": [
        {
            "id": 7,
            "title": "Software engineer",
            "employer": {
                "name": "IBM"
            },
            "location": "MCR",
            "salary": "£45k+"
        }
    ]
}

2 Answers

Steven Parker
Steven Parker
174,022 Points

You're attemting to assign your handler function to "xhr.readyState" but that is a read-only property.

You should assign the handler to "xhr.onreadystatechange" instead.

John Lack-Wilson
John Lack-Wilson
8,158 Points

If you're not receiving any statements in the console, it is most likely because the condition in your if statement is not true / never true.

Try to use console.log outside of your if statement and see what happens, if you get something then you need to change the condition within the if statement.