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)

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay