The $.get() and $.post() methods are the standard way to
communicate with a server via HTTP requests. Unlike the load() method, which
automatically updates the DOM, these methods simply fetch or send the data, giving you
complete freedom to decide what to do with the result.
Before using these methods, you must understand the two most common types of HTTP requests:
| Method | Best Used For... | Security & Size |
|---|---|---|
| GET | Requesting data. It remains in the browser history. | Visible in URL; small data limits. |
| POST | Submitting/Sending data. It is never cached. | Data hidden in "body"; no size limit. |
The $.get() method requests data from the server with an HTTP GET request.
$.get(URL, callback);
$.get("demo_test.php", function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
The $.post() method sends data to the server with an HTTP POST request. This
is commonly used for login forms, registration, or saving profile data.
$.post(URL, data, callback);
$.post("demo_test_post.php",
{
name: "John Doe",
city: "New York"
},
function(data, status) {
alert("Server Response: " + data + "\nStatus: " + status);
}
);
data)
holds the content returned by the server, and the second (status) holds the
status of the request (e.g., "success").
In modern apps, you often fetch JSON data from an API. You can use $.get()
and let jQuery automatically parse the JSON for you.
$.get("https://api.example.com/user/1", function(user) {
// jQuery automatically turns the JSON response into a JS object
$("#name").text(user.first_name + " " + user.last_name);
$("#email").text(user.email);
});
$.post() for anything that creates or
modifies data on your server (like adding a comment). Use $.get() only
for retrieving information.
$.ajax()
function.