DEV Community

Cover image for Intro to Ajax & XHR
Connor Dillon
Connor Dillon

Posted on

4 1

Intro to Ajax & XHR

Synchronous Code

posts = loadPostsSync()
// ... wait til posts are fetched
// ... do something with posts

doTheNextThing() // Has to wait until posts load
Enter fullscreen mode Exit fullscreen mode

Asynchronous Code

loadPostsAsync(function () {
  // ... wait til posts are fetched
  // ... do something with posts
})

doTheNextThing() // Doesn't have to wait until posts load
Enter fullscreen mode Exit fullscreen mode

Most Async code you work with will be part of an API or Library

  • XMLHttpRequest & Fetch
  • jQuery Ajax, Axios, other HTTP Libraries
  • Node.js fs (filesystem) module

A few ways to work with Async code

  • Callbacks
  • Promises (ES6/ES2015)
  • Async/Await

Ajax ("Asynchronous Javascript & XML")

  • Set of web technologies
  • Send & receive data asynchronously
  • Does not interfere with current page
  • JSON has replaced XML for the most part
    • Ajax engine sits between the server and the client as a middleman
    • Client sends JS calls to Ajax Engine
    • Ajax Engine returns HTML response to client
    • Ajax Engine sends XmlHttpRequest to Server
    • Server returns XML/JSON
  • Makes async requests in the background
  • No page reload/refresh needed
  • Fetches data
  • Very interactive

XmlHttpRequest (XHR) Object

  • Core tech in Ajax
  • API in the form of an object
  • Provided by the browser's JS environment
  • Methods transfer data between client & server
  • Can be used with other protocols than HTTP
  • Can work with data other than XML (JSON, plain text)
    • *Nowadays we mostly just work with JSON data

Libraries and Other Methods

  • Fetch API (part of vanilla JS)
  • Axios (external library)
  • Superagent (external library)
  • jQuery (not recommended if just using it for Ajax. jQuery is a complete DOM manipulation library, which is very bloated for just Ajax)
  • Node HTTP (good if using Node.js)

Top comments (0)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay