jQuery $.get() and $.post()

The $.get() and $.post() methods are shorthand versions of $.ajax() with fewer options. They are ideal for simple requests where you do not need full control. $.get() retrieves data from the server. $.post() sends data to the server.

$.get() — Retrieve Data

Syntax

$.get(url, data, callback, dataType);

// Parameters:
// url      → required — server address
// data     → optional — query parameters to send
// callback → optional — function to run on success
// dataType → optional — expected response format

Basic $.get() Example

$(document).ready(function() {
    $("#loadBtn").click(function() {
        $.get("products.json", function(data) {
            $.each(data, function(i, item) {
                $("#list").append("<li>" + item.name + " — ₹" + item.price + "</li>");
            });
        });
    });
});

Clicking the button fetches product data from products.json and builds a list — all without reloading the page.

$.get() with Query Parameters

// Sends: search.php?category=electronics&sort=price
$.get("search.php", { category: "electronics", sort: "price" }, function(response) {
    $("#results").html(response);
});

The data object is converted to URL query parameters automatically.

Diagram: GET Request Flow

  Browser → GET request → search.php?category=electronics&sort=price
                                  │
                          Server processes query
                                  │
                          Server sends back HTML or JSON
                                  │
  Browser ← response ← jQuery runs callback function
                      → updates #results on the page

$.post() — Send Data to Server

Syntax

$.post(url, data, callback, dataType);

Basic $.post() Example

$(document).ready(function() {
    $("#contactForm").submit(function(e) {
        e.preventDefault();

        $.post("send-message.php",
            {
                name:    $("#name").val(),
                email:   $("#email").val(),
                message: $("#message").val()
            },
            function(response) {
                $("#status").text(response);
            }
        );
    });
});

Diagram: POST Request Flow

  Browser → POST request → send-message.php
             (body contains name, email, message)
                                  │
                          Server saves to database
                                  │
                          Server sends "Message sent!"
                                  │
  Browser ← "Message sent!" ← jQuery shows it in #status

GET vs POST — Key Differences

Feature$.get()$.post()
Data locationIn the URL (query string)In the request body
VisibilityVisible in browser URLHidden from URL
Data size limitLimited (URL length ~2000 chars)Much larger
SecurityLess secure (data in URL)More secure for sensitive data
CachingCan be cached by browserNot cached
Use forFetching/searching dataSubmitting/saving data

Handling the Response DataType

// Expect JSON response
$.get("api/user.php", { id: 5 }, function(data) {
    $("#username").text(data.name);
    $("#useremail").text(data.email);
}, "json");

// Expect plain text response
$.get("status.txt", function(data) {
    $("#status").text(data);
}, "text");

// Expect HTML response
$.get("sidebar.html", function(data) {
    $("#sidebar").html(data);
}, "html");

Using Promise Style with $.get() and $.post()

// $.get() with promise
$.get("data.json")
    .done(function(data) {
        console.log("Data received:", data);
    })
    .fail(function() {
        console.log("Request failed");
    });

// $.post() with promise
$.post("save.php", { title: "New Post", content: "..." })
    .done(function(response) {
        alert("Saved with ID: " + response.id);
    })
    .fail(function() {
        alert("Save failed.");
    });

Practical: Live Search with $.get()

$(document).ready(function() {
    $("#searchInput").on("input", function() {
        var query = $(this).val().trim();
        if (query.length < 2) {
            $("#suggestions").empty();
            return;
        }

        $.get("search.php", { q: query }, function(results) {
            $("#suggestions").html(results);
        }, "html");
    });
});

Practical: Rating Submit with $.post()

$(document).ready(function() {
    $(".star").click(function() {
        var rating = $(this).data("value");
        var productId = $("#productId").val();

        $.post("rate.php", { product_id: productId, rating: rating }, function(res) {
            if (res.success) {
                $("#ratingMsg").text("Thanks! You rated: " + rating + "/5");
            }
        }, "json");
    });
});

Quick Summary

  • $.get(url, data, callback, type) fetches data using an HTTP GET request.
  • $.post(url, data, callback, type) sends data using an HTTP POST request.
  • GET data appears in the URL; POST data is hidden in the request body.
  • Use GET for reading/searching; use POST for creating, updating, or sending sensitive data.
  • Both return jQuery Deferred objects, supporting .done(), .fail(), and .always().

Leave a Comment

Your email address will not be published. Required fields are marked *