HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

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

The $.get() and $.post() methods are the standard way to communicate with a server via HTTP requests. Unlike the load() method, which automatically updates the DOM, these methods simply fetch or send the data, giving you complete freedom to decide what to do with the result.


GET vs. POST: The Main Difference

Before using these methods, you must understand the two most common types of HTTP requests:

Method Best Used For... Security & Size
GET Requesting data. It remains in the browser history. Visible in URL; small data limits.
POST Submitting/Sending data. It is never cached. Data hidden in "body"; no size limit.

1. The $.get() Method

The $.get() method requests data from the server with an HTTP GET request.

$.get(URL, callback);
$.get("demo_test.php", function(data, status) {
    alert("Data: " + data + "\nStatus: " + status);
});

2. The $.post() Method

The $.post() method sends data to the server with an HTTP POST request. This is commonly used for login forms, registration, or saving profile data.

$.post(URL, data, callback);
$.post("demo_test_post.php", 
    {
        name: "John Doe",
        city: "New York"
    }, 
    function(data, status) {
        alert("Server Response: " + data + "\nStatus: " + status);
    }
);
Callback Logic: The first parameter in the callback (data) holds the content returned by the server, and the second (status) holds the status of the request (e.g., "success").

Practical Use Case: Fetching JSON

In modern apps, you often fetch JSON data from an API. You can use $.get() and let jQuery automatically parse the JSON for you.

$.get("https://api.example.com/user/1", function(user) {
    // jQuery automatically turns the JSON response into a JS object
    $("#name").text(user.first_name + " " + user.last_name);
    $("#email").text(user.email);
});
Pro Tip: Use $.post() for anything that creates or modifies data on your server (like adding a comment). Use $.get() only for retrieving information.

Key Points to Remember

  • $.get() is for retrieving data (fast and simple).
  • $.post() is for sending data (secure and bulk).
  • Both methods are shorthand for the more complex $.ajax() function.
  • The data returned can be Text, HTML, XML, or JSON.
  • Always provide a callback to handle the data once it arrives from the server.