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

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

jQuery provides two commonly used shorthand methods for making AJAX requests: $.get() and $.post().
These are simplified wrappers around $.ajax() for sending GET and POST requests.


1) jQuery $.get() Method

Definition

The $.get() method sends an HTTP GET request to a server and retrieves data asynchronously without reloading the page.


Syntax

$.get(URL, data, successCallback, dataType);

Parameters

Parameter Description Optional
URL The server or file to request data from Required
data Data sent to the server as query parameters Optional
successCallback Function executed when the request succeeds Optional
dataType Expected response format ("json", "html", "text", "xml") Optional

Basic Example

$.get("info.txt", function(data) {
    $("#result").html(data);
});
  • Fetches info.txt.

  • Injects the result into <div id="result">.


GET with Parameters

$.get("data.php", { name: "John", age: 25 }, function(response) {
    $("#info").html(response);
});
  • Sends name=John and age=25 to data.php.

  • Displays the server response in #info.


GET JSON Response

$.get("users.json", function(data) {
    $.each(data, function(index, user) {
        $("#users").append("<li>" + user.name + "</li>");
    });
}, "json");
  • Fetches users.json.

  • Iterates through JSON data and displays user names.


Error Handling

$.get("invalid.php")
  .done(function(data) {
    $("#status").html("Success: " + data);
  })
  .fail(function(xhr, status, error) {
    $("#status").html("Error: " + xhr.status + " " + xhr.statusText);
  });
  • Uses .done() and .fail() for better handling.


2) jQuery $.post() Method

Definition

The $.post() method sends an HTTP POST request to a server, typically used when submitting forms or sending sensitive data.


Syntax

$.post(URL, data, successCallback, dataType);

Parameters

Parameter Description Optional
URL The server or file to send data to Required
data Data sent in the request body Optional
successCallback Function executed on success Optional
dataType Expected response format Optional

Basic Example

$.post("submit.php", function(data) {
    $("#result").html(data);
});
  • Sends a POST request to submit.php.

  • Inserts the response into #result.


POST with Parameters

$.post("formHandler.php", { username: "Alex", password: "12345" }, function(response) {
    $("#message").html(response);
});
  • Sends username and password securely in the request body.

  • Displays the server’s response in #message.


POST JSON Response

$.post("api/login", { email: "[email protected]", password: "1234" }, function(result) {
    if (result.success) {
        alert("Login Successful!");
    } else {
        alert("Login Failed!");
    }
}, "json");
  • Expects a JSON response.

  • Handles success and failure conditions.


Error Handling

$.post("submitForm.php", { name: "Emma" })
  .done(function(data) {
    alert("Form Submitted Successfully!");
  })
  .fail(function(xhr) {
    alert("Error: " + xhr.status + " " + xhr.statusText);
  });
  • Uses .done() and .fail() for handling failures.


3) Difference Between $.get() and $.post()

Aspect $.get() $.post()
Data Visibility Sent via URL (query params) Sent in request body
Security Less secure More secure
Data Size Limited (URL length restriction) Can handle large amounts
Use Case Fetching data Submitting forms, uploading
Caching Usually cached by browsers Not cached

4) Combined Example

$("#getData").click(function() {
    $.get("products.php", function(data) {
        $("#productList").html(data);
    });
});

$("#postData").click(function() {
    $.post("order.php", { item: "Laptop", qty: 2 }, function(response) {
        $("#orderStatus").html(response);
    });
});
  • The first button fetches data using GET.

  • The second button sends data using POST.


5) Summary

  • $.get() → Fetch data from the server.

  • $.post() → Send data to the server.

  • Both methods are simple alternatives to $.ajax().

  • Use .done(), .fail(), and .always() for better control.

  • Prefer GET for retrieving data and POST for creating or updating data.