The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request.
These are the core methods for interacting with APIs and processing form submissions.
They allow your website to communicate with backend servers dynamically.
Two commonly used methods for a request-response between a client and server are: GET and POST.
GET - Requests data from a specified resource.
GET is basically used for getting (retrieving) some data from the server. Note: The GET method may return cached data.
POST - Submits data to be processed to a specified resource.
POST is basically used to send data to the server to create or update a resource. The POST method never caches data, and is often used to send sensitive data.
The $.get() method requests data from the server with an HTTP GET request.
The syntax is simple: $.get(URL, callback);
The required URL parameter specifies the URL you wish to request.
The optional callback parameter is the name of a function to be executed if the request succeeds.
Here is an example of fetching data from a generic endpoint using the get() method.
The first parameter of the callback function holds the requested content, and the second parameter holds the status of the request.
$("button").click(function(){
$.get("demo_test.asp", function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
The $.post() method requests data from the server using an HTTP POST request.
This method is specifically designed for sending data securely.
The syntax is: $.post(URL, data, callback);
The optional data parameter specifies some data to send along with the request to the server.
Here is an example of using the post() method to send a name and city to an endpoint.
The backend server processes this data, and sends a response back to the client.
$("button").click(function(){
$.post("demo_test_post.asp",
{
name: "Donald Duck",
city: "Duckburg"
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
});
Which HTTP method is best suited for sending sensitive information or updating resources on the server?
Does the GET method typically cache the data returned from the server?