DEV Community

Discussion on: the web developer dream - learn the AJAX technique

Collapse
lukeshiru profile image
LUKESHIRU

FYI nowadays we use fetch instead of XMLHttpRequest. So instead of writing something like this:

const ajax = new XMLHttpRequest();
ajax.addEventListener("readystatechange", ({ currentTarget }) => {
    console.log(currentTarget.readyState, currentTarget.status);
    if (this.readyState == 4 && this.status == 200) {
        // execute what's here
    }
});
ajax.open("GET", "https://myapi.com", true);
ajax.send();
Enter fullscreen mode Exit fullscreen mode

You write it like this:

fetch("https://myapi.com").then(response => {
    if (response.ok) {
        // execute what's here
    }
});
Enter fullscreen mode Exit fullscreen mode

Best thing about fetch is that is based on promises.

One other thing, you might want to avoid innerHTML, which is extremely unsafe. If you really want to take html from the backend and set the front end based on that, you might want to use something like DOMParser.

Cheers!

Collapse
z2lai profile image
z2lai

Haha, I think you're being a little too polite there. It's not really nowadays if it's been like this for 10+ years, especially in the world of web dev.