AJAX (Asynchronous JavaScript and XML) lets a page talk to the server without reloading. Today the data is usually JSON, not XML.
Where AJAX is used
- Live search suggestions
- "Load more" buttons
- Submitting forms without a page refresh
- Checking if a username is available
- Updating cart totals
jQuery AJAX methods
| Method | Use |
|---|---|
.load(url) |
load HTML straight into an element |
$.get(url) |
simple GET request |
$.post(url, data) |
simple POST request |
$.getJSON(url) |
GET and parse JSON |
$.ajax({...}) |
full control over everything |
load()
$('#news').load('/latest-news.html');
$('#news').load('/page.html #content'); // only part of the page
Same-origin rule
Browsers allow AJAX to your own site freely. Other sites must allow it (CORS).
Example
Example — Load JSON without reloading
HTML
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<button id="load">Load a random post</button>
<div id="post" style="margin-top:10px;padding:12px;border:1px solid #ddd;max-width:420px">Click the button.</div>
<script>
$(function () {
$('#load').click(function () {
const id = Math.floor(Math.random() * 100) + 1;
$('#post').text('Loading...');
$.getJSON('https://jsonplaceholder.typicode.com/posts/' + id)
.done(function (data) {
$('#post').empty()
.append($('<h4>').text('#' + data.id + ' ' + data.title))
.append($('<p>').text(data.body));
})
.fail(function () {
$('#post').text('Could not load the post. Check your internet connection.');
});
});
});
</script>
Uses the free JSONPlaceholder test API.
Try it Now »