May 07, 2021 jQuery
The jQuery get() and post() methods are used to request data from the server through HTTP GET or POST requests.
Two common ways to request-respond on the client and server sides are GET and POST.
GET is basically used to get (get back) data from the server. Note: The GET method may return cached data.
POST can also be used to get data from the server. However, the POST method does not cache data and is often used to send data along with requests.
To learn more about GET and POST and the differences between the two approaches, read our HTTP Method - GET Vs POST.
The $.get() method requests data from the server through HTTP GET.
The required URL parameter specifies the URL you want to request.
The optional callback parameter is the name of the function executed after the request is successful.
The following example uses the $.get() method to get data back from a file on the server:
The first parameter of $.get() is the URL we want to request ("demo_test.php").
The second argument is the callback function. The first callback argument contains the contents of the requested page, and the second callback argument has the requested state.
Tip: This PHP file ("demo_test.php") is something like this:
The $.post() method requests data from the server via HTTP POST.
Grammar:
The required URL parameter specifies the URL you want to request.
The optional data parameter specifies the data sent along with the request.
The optional callback parameter is the name of the function executed after the request is successful.
The following example uses $.post() to send data along with the request:
The first parameter of $.post() is the URL we want to request ("demo_test_post.php").
Then we send the data along with the request (name and city).
PhP demo_test_post.php in "2007" reads these parameters, processes them, and returns the results.
The third argument is the callback function. The first callback argument contains the contents of the requested page, while the second argument has the requested state.
Tip: This PHP file ("demo_test_post.php") is something like this:
Tip: In jQuery, the $.ajax() method achieves the same functionality as the load(), $.get() and $.post () methods, and has more effect!