Javascript Xmlhttprequest if Error Make Request Again

Photo by NASA on Unsplash

What is a network request

Whenever you submit a url from your web browser's address bar, you make an HTTP request to a server. What you receive from that request is an HTML document, the website that you requested. HTTP is the protocol that allows usa to do that.

What AJAX is useful for

In HTML, we can link to other documents using the a element. After clicking a link like that nosotros get redirected to another page, specified in the href attribute. The problem is, the entire page needs to reload. What if nosotros don't want our users to stare at a white screen? Mayhap we need to call back some data from the server only only want to replace a role of our folio? That's where AJAX comes in.

What is AJAX

AJAX (Asynchronous JavaScript And XML) is simply a fashion of using JavaScript to fetch data from the server without reloading the website. XML is a data format similar to html, but present JSON is more common. JSON (JavaScript Object Annotation) is data in the form of JavaScript objects. Information technology's the format in which we want to be receiving data from the server. Using AJAX, we can asynchronously asking some data in the background with JavaScript and display information technology to the user once nosotros receive information technology. We no longer need to reload the entire page.

Using an API

To get that data we will employ something called Awarding Programming Interface. Information technology is a way of communication between software. It will provide our JavaScript code with a way to make requests to a server. All we need to do in our example is to use a specific url and the server will return data to united states based on that url. That'southward how we can make an API call. In this example, we will exist using a publicly available API to get random pictures of dogs. Pretty awesome, right?

Making requests with the XHR object.

In order to make an ajax request, we will utilise an XMLHttpRequest object. Let'due south set up the boilerplate code. Get-go, we want to create the object using the constructor:

          const xhr = new XMLHttpRequest()        

At present nosotros need to specify the HTTP method that nosotros are going to use. We are going to apply the GET method. Basically, it means that if nosotros were to pass whatever parameters to the API, nosotros would put them straight in the url. We as well need to provide the url from which we want to get the information. That'south the API.

          const url = 'https://random.dog/woof.json'
const xhr = new XMLHttpRequest()
xhr.open('GET', url)

Yous can paste the url into your browser and see what comes up. The information that comes back to our xhr object is in the form of a string by default, simply we can asking an object. Let'southward exercise that.

          const url = 'https://random.dog/woof.json'
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'

Here comes the important part. We want to pass a callback function to our xhr object that will run when the data comes dorsum.

          const url = 'https://random.dog/woof.json'          const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'
xhr.onload = () => console.log(xhr.response)

It's just like specifying an onclick handler. The provided function will run in one case the request completes. Permit'southward log the data that we get from the server. Information technology's in the response property of our xhr object.

Now, to transport the asking, we take to call the send method:

          const url = 'https://random.dog/woof.json'          const xhr = new XMLHttpRequest()
xhr.open('Get', url)
xhr.responseType = 'json'
xhr.onload = () => console.log(xhr.response)
xhr.send()

Hurray! We get an object with the size of the epitome and the url that links to it. Obviously, logging it to the panel isn't that exciting, but i leave it up to y'all to make employ of what you've learned. Hint: You lot tin can make a website where, every time y'all click a push, a random dog moving-picture show shows up.

XHR is asynchronous

Because a network request takes time to complete, xhr is asynchronous by default. Information technology means that, if we try to admission the issue of our asking before it finishes, we will get null.

          const url = 'https://random.dog/woof.json'          const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.responseType = 'json'
xhr.onload = () => console.log(xhr.response)
//Callback function logs the response in one case the asking completes
xhr.send()
panel.log(xhr.response)
//Synchronous console.log runs before the asynchronous network asking completes, prints null

Error handling with XHR

In a existent awarding, when performing network requests, the user will oftentimes run into errors, for example when they lose their net connectedness or when the requested recource couldn't be found.

When a asking couldn't exist sent at all, the fault event runs. Nosotros tin can specify what to do when that happens by passing another callback:

          xhr.onerror = () => console.log('At that place was a network error. Check your net connectedness and endeavor again.')        

This volition merely run when the request couldn't be made. That happens when in that location is no net connection or the url is invalid.

The load upshot volition run even if the condition of the response is, for instance, 404. That'south why we need to cheque the status inside the onload callback:

          xhr.onload = () => {
if (xhr.condition !== 200) {
console.log(`Error ${xhr.condition}: ${xhr.statusText}`)
} else {
console.log(xhr.response)
}
}

If everything went right, the condition will exist 200. We can go the status code from xhr.status and the respective bulletin from xhr.statusText. If there was an error, the effect of our console.log would be something like "Fault 404: Not found".

This is the terminal code with error handling implemented:

          const url = 'https://random.canis familiaris/woof.json'          const xhr = new XMLHttpRequest()
xhr.open up('GET', url)
xhr.responseType = 'json'
xhr.onload = () => {
if (xhr.status !== 200) {
console.log(`Error ${xhr.status}: ${xhr.statusText}`)
} else {
console.log(xhr.response)
}
}
xhr.onerror = () => console.log('In that location was a network error. Check your internet connection and try once again.') xhr.send()

Replace the url with something similar "https://random.dog/woof.json/aaa" to bank check if the 404 is handled properly. You tin as well replace the url with an invalid one such as "https://aaa" to see the onerror event handler in action.

Conclusion

XHR provides us with a fashion of asynchronously making network requests. Nosotros gear up things up, provide a url, load and error handlers, then transport the request. If y'all want to learn more most XHR, for instance, how to determine the progress of the request, check out this article.

Network requests in modernistic JavaScript

XHR requires quite a bit of boilerplate code. We need to construct the object, gear up the HTTP method every time and explicitly ship the request. It as well relies on callback functions which can get messy in complex scenarios if not handled properly. In mod JavaScript, we employ a function chosen fetch for network requests. Information technology uses ES6 Promises and information technology's more flexible and powerful. Check out my article on fetch and Promises to learn how to simplify network requests!

johnsonwomic1952.blogspot.com

Source: https://medium.com/swlh/intro-to-ajax-and-xhr-network-requests-in-javascript-41738093fe00

0 Response to "Javascript Xmlhttprequest if Error Make Request Again"

Publicar un comentario

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel