
Get And Post in Jquery
In jQuery, GET
and POST
are two commonly used AJAX methods to request or send data to a server without reloading the page.
They are used for:
GET: Requesting data from a server.
POST: Sending data to a server (like form submission).
? 1. $.get()
– HTTP GET Request
? Syntax:
$.<button "#loadUser").click(function () { $.get("user.php", { id: 1 }, function (data) { $("#userInfo").html(data); }); });</script>
This sends GET user.php?id=1
, and displays the response inside the #userInfo
div.
? 2. $.post()
– HTTP POST Request
? Syntax:
$.<form "#myForm").submit(function (e) { e.preventDefault(); // Prevent default form submission $.post("submit.php", $(this).serialize(), function (data) { $("#response").html(data); }); });</script>
This submits form data via POST
to submit.php
and shows the server response in the #response
div.
? Difference Between .get()
and .post()
Feature | .get() | .post() |
---|---|---|
Purpose | Fetch data | Send data |
Data visible? | Yes, in URL | No, hidden in request body |
Max size? | Limited | No strict limit |
Use cases | Loading content, getting data | Form submission, saving/updating data |
? Pro Tip: Using .done()
for Better Structure
$.post("submit.php", {name: "Jane"}) .done(function(response) { console.log("Success:", response); }) .fail(function(error) { console.log("Error:", error); });