Explain Codes LogoExplain Codes Logo

How can I make an AJAX call without jQuery?

javascript
ajax
http-requests
async-communication
Nikita BarsukovbyNikita BarsukovΒ·Nov 5, 2024
⚑TLDR
// Use XMLHttpRequest const xhr = new XMLHttpRequest(); xhr.open("GET", "your/endpoint", true); // (Woops! Not a real URL πŸ˜‰) // Wait for a response xhr.onload = () => { if (xhr.status === 200) { // "HTTP 200: Everything is A-OK" πŸ†— const data = JSON.parse(xhr.response); console.log(data); // Our lovely response } else { console.error("Something went sideways πŸ™ƒ"); // Unexpected status code } }; xhr.send(); // Off it goes!

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):

xhr.onreadystatechange = function() { // The gauntlet has been thrown if (xhr.readyState === XMLHttpRequest.DONE) { if (xhr.status === 200) { // Another happy landing console.log(JSON.parse(xhr.responseText)); // The treasure } else { // Are you not entertained?! (eg: errors) console.error("Whoopsie daisy 🌼"); } } };

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:

// Start the fetch fetch('your/endpoint') .then(response => { if (!response.ok) throw new Error('Fetch fumbled 🏈'); return response.json(); // Fumbles pass to JSON }) .then(data => console.log(data)) // Data touchdown! .catch(error => console.error('πŸ”₯ Fetch on fire:', error)); // Fumble recovery

Spice it up further with async/await:

// Upgraded fetch async function fetchData(url) { try { // Try to catch the wild fetch const response = await fetch(url); if (!response.ok) throw new Error('Gotcha! Fetch escaped πŸƒβ€β™‚οΈ'); const data = await response.json(); console.log(data); // Gotcha! Data captured } catch (error) { console.error('Fetch is *really* upset:', error); } } fetchData('your/endpoint');

Fetch API pops clean, readable code and spare ribs for lunch!

Wiring it all

AJAX's 'Eureka!' moments

When making an AJAX call:

  1. Handle errors like a pirate handles rum.
  2. Test across browsers. Code so even Internet Explorer can't egg your face.
  3. Timeouts: Not everyone has Gigabit and 5G.
  4. Sanitize inputs/outputs. Cholera kills websites, too.
  5. 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.get('your/endpoint') .then(response => console.log(response.data)) .catch(error => console.error('No soup for you!', error));

Axios advantages:

  • Automatic JSON data transformations.
  • Interception of request and response.
  • Ability to cancel requests.
  • Better error handling.