Pulling json data from API call using XHR

Hi - I have the following code that does a GET request to the url and also passes the apiKey. From the console at the browser level, i am able to see the content of xmlHttp, so that means that the GET request works.

However, my console.log does not seem to return on the console output. My goal is not just to console.log the get output but after checking that it works, i somehow going to parse the data.

Can anyone advise what im doing wrong?

const xmlHttp = new XMLHttpRequest();
const url = 'https://randomurl.com?id=222';
xmlHttp.open("GET", url);
xmlHttp.setRequestHeader('apiKey', 'xxxxxxxxxxx');
xmlHttp.send();

xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        
        console.log(xmlHttp);
    }
}

Are you sure that the xmlHttp.status is exactly 200? Try listening for a range of status numbers, as in this example.

Yes it is, Screen Shot 2021-02-12 at 12.23.43 PM

Actually i just noticed that the condition is not relevant. If i comment out that part i can still access xmlHttp over the console. For example:

If i modify condition like this:

xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4) {
        console.log(xmlHttp);
    }
}

The readyState is true on the xmlHttp, so it should execute console.log(xmlHttp); but its not.

Hi,

One possible way to write a function and call it where you call console.log.

Example:
// your AJAX call:
...
   if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
       // call your function here 
       myFunction();
    }
...

const myFunction = () => {
// my code goes here...
}

Another possible way to create an asyncron code:

async
const callAJAX = () => {
    return new Promise(waitForResponse => {
        const xmlHttp = new XMLHttpRequest();
        const url = 'https://randomurl.com?id=222';
        xmlHttp.open("GET", url);
        xmlHttp.setRequestHeader('apiKey', 'xxxxxxxxxxx');
        xmlHttp.send();

        xmlHttp.onreadystatechange = function () {
            if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        
                 waitForResponse(this.response);
            }
        }
    }); 
};

// and you can call your asyncron ajax here:
callAJAX().then(data => {
           // to do somethings with the data....
                console.log(data);
            });
At least here is my AJAX function:
const callAJAX = (props) => {
    const url = props.url,
          method = props.method || "GET",
          type = props.type || "JSON",
          header = props.header
    ;
    return new Promise(waitForResponse => {
        const xhttp = new XMLHttpRequest();
        if (method === "GET") {
            xhttp.open("GET", url, true);
            for (const key in header) {
                xhttp.setRequestHeader(key, header[key]);
            }
            xhttp.send();
        } else {
            xhttp.open(method, url, true);
            for (const key in header) {
                xhttp.setRequestHeader(key, header[key]);
            }
            xhttp.send(props.data);
        }
        xhttp.onreadystatechange = function() {
            if (this.readyState === 4 && this.status === 200) {
//                console.log(this.response);
                type === "text"
                    ? waitForResponse(this.response)
                    : waitForResponse(JSON.parse(this.response))
                ;
            }
        };
    });
};

// I call AJAX here using JSON:
const props = {
    url: "http://localhost:5000/profile",
    method: "PUT",
    header: {
        "Content-type": "application/json"      // without this header data will send as a text!!!
    }, 
    data: `${JSON.stringify(data)}`
};
            
callAJAX(props).then(data => {
    console.log(data);
});

Hmm… I copy/pasted your code and used a different URL and it worked.

const xmlHttp = new XMLHttpRequest();
const url = 'https://ron-swanson-quotes.herokuapp.com/v2/quotes';
xmlHttp.open("GET", url);
//xmlHttp.setRequestHeader('apiKey', 'xxxxxxxxxxx');
xmlHttp.send();

xmlHttp.onreadystatechange = function () {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        
        console.log(xmlHttp);
    }
}

NOTE: I had to comment out the setRequestHeader or it would give me a Cross-Origin Request Blocked error since it wasn’t expecting that.

Are you getting any errors in the JS console?

Yes for the cors error on Chrome, so i am using safari tech previewer and disabled cors policy at browser level.

However, i just noticed that safari tech previewer was filtering my logs. The console.log is actually there lol. Thanks for checking.

Do you have any recommendation how i can parse “responseText” that is in json format? My goal is to display this data inside a div.

Thanks for the feedback, this method looks sort of complex for me as a beginner thought, although i will review it i can learn sometime from this too.

For now, I just need to GET the data from the api call and parse it.

Definitely. Take a look at the JSON.parse method.