jQuery - Shorthand AJAX Methods in jQuery
What Are Shorthand AJAX Methods?
jQuery provides short, easy-to-use AJAX methods for the most common HTTP requests (GET, POST, and loading content).
They are simpler versions of the full $.ajax()
function.
1. $.get()
-
Used for sending a GET request to fetch data from the server.
-
Syntax:
$.get(url, data, successCallback);
Example:
$.get("data.txt", function(response) {
console.log("Data from server: " + response);
});
This fetches the contents of data.txt
and logs it.
2. $.post()
-
Used for sending a POST request (often for sending form data).
-
Syntax:
$.post(url, data, successCallback);
Example:
$.post("submit.php", { name: "John", age: 25 }, function(response) {
console.log("Server reply: " + response);
});
This sends data (name
and age
) to submit.php
using POST.
3. $.getJSON()
-
Special GET request that expects a JSON response.
-
Syntax:
$.getJSON(url, data, successCallback);
Example:
$.getJSON("users.json", function(data) {
$.each(data, function(index, user) {
console.log(user.name + " - " + user.age);
});
});
This loads a JSON file and prints each user’s name and age.
4. .load()
-
Loads HTML content directly into an element.
-
Syntax:
$("#element").load(url);
Example:
$("#content").load("about.html");
This loads about.html
into the #content
div.
Summary Table
Method | Purpose | Example |
---|---|---|
$.get() |
Send GET request, fetch data | $.get("data.txt", callback) |
$.post() |
Send POST request, send data | $.post("submit.php", {name:"John"}, callback) |
$.getJSON() |
GET request, expects JSON data | $.getJSON("data.json", callback) |
.load() |
Load HTML into a selected element | $("#box").load("info.html") |