$.get and $.post

Send simple GET and POST requests for data.

Syntax$.get(url, callback); $.post(url, data, callback);

These shorthand methods fetch or send data:

  • $.get(url, data, callback) — request data (safe, no side effects).
  • $.post(url, data, callback) — send data to create or change something.
$.get("/api/user", function (data) {
  console.log(data);
});

$.post("/api/save", { name: "Ada" }, function (res) {
  console.log("Saved", res);
});

Example

Try it yourself
Loading editor…
Press Run to see the result.

When to use it

  • A search autocomplete uses $.get('/api/suggest?q=...') to fetch matching terms as the user types.
  • A contact form uses $.post('/api/contact', formData) to submit without a page reload and shows a confirmation.
  • A weather widget uses $.get() with query parameters to fetch the current temperature for the user's city.

More examples

GET request with query parameters

The third argument to $.get() is a plain object that jQuery serializes into the query string automatically.

Example · html
<input id="city" placeholder="City name" />
<button id="getWeather">Get weather</button>
<p id="weather"></p>
<script>
$(function () {
  $("#getWeather").click(function () {
    var city = $("#city").val();
    $.get("/api/weather", { city: city }, function (data) {
      $("#weather").text(city + ": " + data.temp + "°C");
    });
  });
});
</script>

POST form data with $.post()

$(this).serialize() encodes all form fields as a URL-encoded string that $.post() sends as the request body.

Example · html
<form id="contact">
  <input name="name" placeholder="Name" />
  <input name="email" placeholder="Email" />
  <button type="submit">Send</button>
</form>
<p id="confirm"></p>
<script>
$(function () {
  $("#contact").on("submit", function (e) {
    e.preventDefault();
    $.post("/api/contact", $(this).serialize(), function () {
      $("#confirm").text("Message sent!");
    });
  });
});
</script>

Chain .done() and .fail() on $.get()

$.get() returns a jqXHR Deferred; chaining .done() and .fail() separates success and error handling cleanly.

Example · html
<button id="load">Load user</button>
<div id="profile"></div>
<script>
$(function () {
  $("#load").click(function () {
    $.get("/api/user/1")
      .done(function (user) {
        $("#profile").text(user.name + " — " + user.email);
      })
      .fail(function (xhr) {
        $("#profile").text("Error: " + xhr.status);
      });
  });
});
</script>

Discussion

  • Be the first to comment on this lesson.