jQuery get() and post()
$.get() and $.post() are short helpers for the two most common HTTP methods. They are thin wrappers around $.ajax(), so everything they return supports .done(), .fail(), .always() and .then().
GET vs POST
| GET | POST | |
|---|---|---|
| Purpose | Read data | Send data / change something |
| Data travels in | The URL query string: /search?q=tea |
The request body |
| Cached by browsers | Can be | No |
| Typical use | Search, load a list, fetch a record | Submit a form, create an order, log in |
| Safe to repeat | Yes | Not necessarily (may create duplicates) |
$.get()
$.get(url, data, success, dataType);| Argument | Meaning |
|---|---|
url |
Where to send the request |
data (optional) |
Object or string — appended to the URL as a query string |
success (optional) |
function (data, textStatus, jqXHR) |
dataType (optional) |
"json", "html", "text", "xml"… — otherwise guessed from the response's Content-Type |
$.getJSON(url, data, success) is $.get with dataType: "json".
Real-world code looks like this:
$.get("/api/products", { category: "tea", page: 2 }, function (products) {
renderProducts(products);
}, "json");
// → GET /api/products?category=tea&page=2A search box with $.get
The fake server below answers GET /api/search?q=... by filtering a list. The request code is what you would write against a real API.
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
#results li { margin: 2px 0; }
#state { color: #888; font-size: 12px; }
</style>
</head>
<body>
<input id="q" placeholder="Search fruit… (try 'an')" autocomplete="off"> <span id="state"></span>
<ul id="results"></ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// ---- fake server: GET /api/search?q=… ----
const FRUIT = ["apple", "banana", "cherry", "mango", "orange", "papaya", "pineapple", "tangerine"];
$.ajaxTransport("+*", function (options) {
if (!options.url.startsWith("/api/")) return;
let t;
return {
send(headers, complete) {
const q = new URL(options.url, "http://x").searchParams.get("q") || "";
t = setTimeout(() => complete(200, "OK",
{ text: JSON.stringify(FRUIT.filter(f => f.includes(q.toLowerCase()))) }), 250);
},
abort() { clearTimeout(t); }
};
});
// ------------------------------------------
let pending = null;
$("#q").on("input", function () {
const q = $(this).val().trim();
if (pending) pending.abort(); // cancel the previous, now outdated request
if (!q) { $("#results").empty(); $("#state").text(""); return; }
$("#state").text("searching…");
pending = $.get("/api/search", { q: q }, null, "json")
.done(function (matches) {
$("#results").empty().append(matches.map(m => $("<li>").text(m)));
$("#state").text(matches.length + " result(s)");
console.log("q =", q, "→", matches);
})
.fail(function (xhr, status) {
if (status !== "abort") $("#state").text("error");
});
});
</script>
</body>
</html>Calling .abort() on the previous jqXHR prevents an old, slow response from overwriting newer results — a classic bug in search boxes.
$.post()
$.post(url, data, success, dataType);The arguments are the same as $.get, but data is sent in the request body, encoded like a form (name=Ana&qty=2) by default. To send JSON instead, use $.ajax() with contentType: "application/json" (next lesson).
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: sans-serif; font-size: 14px; }
form input, form select { margin: 3px 0; padding: 4px; }
#log li { color: #2e7d32; }
</style>
</head>
<body>
<form id="order">
<input name="name" placeholder="Your name" required>
<select name="drink"><option>Latte</option><option>Espresso</option><option>Tea</option></select>
<input name="qty" type="number" value="1" min="1" style="width:50px">
<button>Place order</button>
</form>
<ul id="log"></ul>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
// ---- fake server: POST /api/orders ----
let nextId = 100;
$.ajaxTransport("+*", function (options) {
if (options.url !== "/api/orders") return;
let t;
return {
send(headers, complete) {
const body = Object.fromEntries(new URLSearchParams(options.data)); // decode the form body
t = setTimeout(() => complete(201, "Created",
{ text: JSON.stringify({ id: nextId++, ...body, status: "received" }) }), 400);
},
abort() { clearTimeout(t); }
};
});
// ---------------------------------------
$("#order").on("submit", function (e) {
e.preventDefault();
const $btn = $(this).find("button").prop("disabled", true).text("Sending…");
const formData = $(this).serialize();
console.log("POST body:", formData);
$.post("/api/orders", formData, null, "json")
.done(function (order) {
$("<li>").text("Order #" + order.id + ": " + order.qty + " × " + order.drink + " for " + order.name)
.appendTo("#log");
console.log("server replied:", order);
})
.fail(() => alert("Could not place the order"))
.always(() => $btn.prop("disabled", false).text("Place order"));
});
</script>
</body>
</html>The .always() handler re-enables the button whether the request succeeded or failed.
The jqXHR object
Every AJAX method except .load() returns a jqXHR:
| Member | Meaning |
|---|---|
.done(fn) |
Success: fn(data, textStatus, jqXHR) |
.fail(fn) |
Error: fn(jqXHR, textStatus, errorThrown) |
.always(fn) |
Runs after either |
.then(ok, err) |
Promise-style chaining |
.abort() |
Cancels the request |
.status, .statusText |
HTTP status, e.g. 404, "Not Found" |
.responseText, .responseJSON |
Raw text, and parsed JSON when the response was JSON |
.getResponseHeader(name) |
Read a response header |
Note: The old
.success(),.error()and.complete()methods on jqXHR were removed in jQuery 3. Use.done(),.fail()and.always().
Test yourself
Where does $.get("/api/items", { page: 2 }) put the data?
- In the request body
- In the URL:
/api/items?page=2 - In a cookie
- In a custom header
Which handler runs after a request whether it succeeded or failed?
.done().fail().always().success()
Why abort the previous request in a type-ahead search?
- To save the user's typing
- So an old, slow response cannot overwrite newer results
- Because jQuery allows only one request at a time
- To clear the cache