jQuery AJAX cheat sheet

I know the Fetch API is probably going to replace AJAX, and soon.

I also know that learning jQuery is less important now than it has been for a number of years.

However, jQuery Ajax commands are very useful, compact, and still necessary for many APIs. So these ready-to-use code snippets for every day can really come in handy when you just need to get some external data into your HTML quickly and easily.

The snippets cover $.get()$.post()$.load(), $.getJSON, JSON.parse() (which is pure JavaScript), and the all-purpose form tool, $.serialize(). They do not cover $.ajax(), which essentially does everything, but with more lines.

Fetch API: better than AJAX?

“A Promise-based mechanism for programmatically making web requests in the browser.” Replaces most uses of XMLHttpRequest in traditional web applications.

See more links at the end of this post.

Example 1 (run in console):

fetch('http://mindymcadams.com/index.html').then(response => {
   return response.text();
}).then(text => {
   console.log(text);
});

Example 2 (run in console with animals.json file in same dir as the currently open page):

fetch('animals.json').then(response => {
   return response.json();
}).then(json => {
   console.log(json);
});

Each of the examples returns the full contents of the file.

Some good stuff:

  • Working with the Fetch API — this is really clear, step by step, complete (from Google Developers; part of the PWAs workshop, but this can stand alone)
  • Slides that provide an overview of fetch()
  • Introduction to fetch() (also from Google Developers)
  • A window.fetch JavaScript polyfill (on GitHub): “Chrome and Firefox both implement the window.fetch function natively, [so] no code from this project actually takes any effect in these browsers.”