How can I make an AJAX call without jQuery?
Key concepts here include XMLHttpRequest, open(), onload, status, and response. You gotta replace "your/endpoint"
with actual API endpoint URL. Handling the response is up to you, friend.
Complex Gutenberg Printing Press (XMLHttpRequest)
The big and old XMLHttpRequest (XHR) is the grandpa of JavaScript async communication. It carries your HTTP requests to server and hands you back data. Like a well-trained owl from Hogwarts π¦
On readyState's wings
Event listeners will rock your XHR world. They respond to every scrunch of grandpa's old face (state changes):
See status and readyState checking here, hopscotching our way through error and success handling!
XHR vs Yoga class
Pros of XMLHttpRequest:
- It's like being a kid in a candy store, so many options!
- See everything happening, real-time, from start to finish.
Cons:
- More confusing than an Ikea manual.
- Error handling is sort of like catching soap in the shower.
Modern Art (Fetch API)
Fetch API is the cool kid in town, our XMLHttpRequest's fashion-forward grandkid:
Spice it up further with async/await
:
Fetch API pops clean, readable code and spare ribs for lunch!
Wiring it all
AJAX's 'Eureka!' moments
When making an AJAX call:
- Handle errors like a pirate handles rum.
- Test across browsers. Code so even Internet Explorer can't egg your face.
- Timeouts: Not everyone has Gigabit and 5G.
- Sanitize inputs/outputs. Cholera kills websites, too.
- Cancel unnecessary requests. An argument against hoarding.
Gotchas!
- CORS: Either get permission from the server or duel it with a proxy.
- Parsing data: Check data type to avoid "Surprise!"
- Network issues: Swift like a coursing river but sometimes a stubborn mule...have a plan B!
Swanky third-party HTTP libraries
Beyond vanilla JS, there's Axios. Like a Butler, it takes good care of your HTTP requests:
Axios advantages:
- Automatic JSON data transformations.
- Interception of request and response.
- Ability to cancel requests.
- Better error handling.
Was this article helpful?