# JS Tip of the Day: fetch is the new XMLHttpRequest

**URL:** <https://forum.kirupa.com/t/js-tip-of-the-day-fetch-is-the-new-xmlhttprequest/643156>\
**Category:** web dev\
**Created:** [March 11, 2020, 2:02pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-fetch-is-the-new-xmlhttprequest/643156 "2020-03-11T14:02:28Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![senocular](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/senocular/32/7217_2.png) [@senocular](https://forum.kirupa.com/u/senocular)\
**Post date:** [March 11, 2020, 2:02pm UTC](https://forum.kirupa.com/t/js-tip-of-the-day-fetch-is-the-new-xmlhttprequest/643156/1 "2020-03-11T14:02:28Z")

</div>

**fetch is the new XMLHttpRequest**  
Level: Beginner

The introduction of `XMLHttpRequest` was a game changer for JavaScript on the web. It allowed websites to pull data directly from the server rather than having the user have to reload or navigate to another page. Unfortunately, as an API, it has not aged very well and can be difficult to work with. Your standard `XMLHttpRequest` request might have looked something like:

```javascript
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
    if (this.readyState == 4 && this.status == 200) {
       // do stuff
    }
};
xhr.open('GET', 'url', true);
xhr.send(null);

```

A newer API for loading data now exists that’s easier to use and uses modern language features like promises. This comes in the form of the `fetch()` function. `fetch()` takes a url and returns a promise that resolves when a response from loading the url is available.

```javascript
fetch('url')
    .then(response => {
        if (response.ok) {
            // do stuff
        }
    });

```

Despite its apparent simplicity, `fetch()` offers a lot more features beyond what the basic example above demonstrates. See the fetch link below for more on those features and additional examples.

More info:

- [XMLHttpRequest on MDN](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest)
- [fetch on MDN](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch)
- [Using promises on MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises)
