DEV Community

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

lukeshiru profile image

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
});"GET", "", true);
Enter fullscreen mode Exit fullscreen mode

You write it like this:

fetch("").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.


z2lai profile image

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.