jQuery Get and Post
When you need more control than load() gives you, jQuery offers $.get() and $.post(). Both talk to the server, but they use the two most common HTTP request methods, and knowing when to use each is an important habit.
GET versus POST
GET is for reading. You use it to ask the server for data, and any values you send travel visibly in the URL as a query string. POST is for sending. You use it to submit data that will change something on the server, like saving a form, and the values travel hidden in the body of the request. As a rule of thumb: use GET to fetch, use POST to send.
The $.get() method
$.get() takes the URL you want to request and an optional callback function that runs when the data comes back. You can also pass data as a second argument, jQuery turns it into a query string for you.
Requesting data with $.get()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="loadBtn">Load Data</button>
<div id="result"></div>
<script>
$("#loadBtn").click(function() {
$.get("demo_get.php", function(data, status) {
$("#result").html(data);
console.log("Status: " + status);
});
});
</script>
</body>
</html>The callback here receives two arguments: data, the content returned by the server, and status, a short string telling you whether the request succeeded. You can send parameters too, and they will appear in the URL.
Sending parameters with $.get()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<div id="results"></div>
<script>
$.get("search.php", { keyword: "jquery", page: 2 }, function(data) {
// The server receives search.php?keyword=jquery&page=2
$("#results").html(data);
});
</script>
</body>
</html>The $.post() method
$.post() works almost the same way, but the data you pass is tucked into the request body instead of the URL. This is what you want when submitting a form or saving information, the values stay out of the address bar and there is no practical length limit.
Sending data with $.post()
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
</head>
<body>
<button id="saveBtn">Save</button>
<div id="message"></div>
<script>
$("#saveBtn").click(function() {
$.post("save_user.php",
{
name: "Ada Lovelace",
email: "ada@example.com"
},
function(response, status) {
$("#message").text("Server said: " + response);
}
);
});
</script>
</body>
</html>- Reach for $.get() when you are only reading data and nothing changes on the server.
- Reach for $.post() when you are creating, updating, or deleting something.
- The second argument is the data object, jQuery formats it for the request automatically.
- The callback runs asynchronously once the server responds, so put your page updates inside it.
Exercise: jQuery Get and Post
What is the main difference in how $.get() and $.post() send data to the server?