Introduction to jQuery post
jQuery post method requests data from the server using HTTP post request. This method sends an asynchronous request to the server to submit the data to the server and get the response. jQuery.post() method returns an XML HTTP request object. This method is an AJAX method and is used to call server pages like .aspx or .php. POST method is identical to GET method in jQuery, using $.get() or $.post(), depends on the server-side requirements. In case of a large amount of data being transmitted, for ex., form data, a POST request is to be used instead of a GET request as GET has a strict limit on data transfer to and fro on the server.
Syntax
The basic syntax for the jQuery post request can be written as below:
jQuery.post( url [, data ] [, success ] [, dataType ] )
Parameters
1. url: Required parameter with data type String containing the request URL to which the request has to be sent or request from where data has to be received.
2. data: JSON data, which as to be sent to the server. An optional parameter with data type as Plain Object or a String that is sent to the server with the request url.
3. success: It is an optional parameter, a callback function which is executed if the request method succeeds or when data is loaded successfully.
Mandatory parameter if dataType is provided, but can also take null value in such cases. Can also be written a function(data, status,xhr), data contains the resulting data, status contains the status of the request processed; may it be a timeout, success, parsing error, etc., and xhr contains the XMLHttpRequest object.
4. dataType: It is an optional parameter and represents the type of data(string) to be returned as a callback function; response can be in the form of xml, script, json, html, jsonp or text.
- XML being an XML document.
- The script runs as JavaScript and returns plain text.
- JSON runs as JSON and returns a JavaScript object.
- HTML, plain text.
- Jsonp loads a JSON block using JSONP and add a callback to the request URL specifying the callback. Text, plain text string.
In a simple format, jQuery post syntax can also be written as:
$.post( URL, data, callback);
Let us see How this jQuery is.post() method used?
jQuery script has to be used while implementing, i.e., can be of any version:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Examples of jQuery post
Given below are the examples mentioned:
Example #1
jQuery post with simple click functionality.
Code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function () {
$('#jQuerybutton').click(function(){
// request URL
$.post('/jquery/submitData',
// data submitted to POST request
{ myData: 'Data has been sent successfully using jQuery POST' },
// callback function on success
function(data, status, jqXHR) {
$('p').append('sent status: ' + status + ', data sent: ' + data);
});
});
});
</script>
</head>
<body>
<h1> jQuery post() method with a simple click function
</h1>
<input type="button" id="jQuerybutton" value="POST your request here" />
<p>
</p>
</body>
</html>
Output:
On click:
Example #2
jQuery post method.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery POST Request using AJAX</title>
<style>
label{
display: block;
margin-bottom: 15px;
color: red
}
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("form").submit(function(eventObj){
eventObj.preventDefault();
var actionBtn = $(this).attr("action");
var formValue = $(this).serialize();
$.post(actionBtn, formValue, function(empdata){
$("#resultData").html(empdata);
});
});
});
</script>
</head>
<body>
<form action="/php/empComment.php">
<label>Your Employee Name: <input type="text" name="empname"></label>
<label>Comments for improvement: <textarea cols="25" name="empcomment"></textarea></label>
<input type="submit" value="Send Here">
</form>
<div id="resultData"></div>
</body>
</html>
In empComment.php
<?php
$name = htmlspecialchars($_POST["empname"]);
$comment = htmlspecialchars($_POST["empcomment"]);
echo "Hi, $empname. Your comment has been received successfully." . "";
echo "Here's the comment what you've entered: $empcomment";
?>
Output:
On entering values:
On submitting:
Example #3
jQuery post method || Submit Form.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery POST method||Submit Form page</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("form").on("submit", function(eventObj){
eventObj.preventDefault();
var htmlFormValues= $(this).serialize();
var submitAction = $(this).attr("action");
$.post(submitAction, htmlFormValues, function(formData){
$("#formResult").html(formData);
});
});
});
</script>
</head>
<body>
<form action="/php/formProcess.php">
<p>
<label>Your Name:</label>
<input type="text" name="name">
</h3>
<p>
<label>Please specify Gender:</label>
<label><input type="radio" value="male" name="gender"> Male</label>
<label><input type="radio" value="female" name="gender"> Female</label>
<label><input type="radio" value="transgender" name="gender"> Transgender</label>
</h3>
<p>
<label>Your Hobbies:</label>
<label><input type="checkbox" value="Reading Books" name="hobbies[]"> Reading Books</label>
<label><input type="checkbox" value="Driving" name="hobbies[]"> Driving</label>
<label><input type="checkbox" value="Music" name="hobbies[]"> Music</label>
<label><input type="checkbox" value="Dancing" name="hobbies[]"> Dancing</label>
<label><input type="checkbox" value="Sports(Indoors/ Outdoors)" name="hobbies[]"> Sports(Indoors/ Outdoors)</label>
</h3>
<p>
<label>Your Favorite Color:</label>
<select name="color">
<option>BLUE</option>
<option>YELLOW</option>
<option>GREEN</option>
<option>ORANGE</option>
<option>BLACK</option>
</select>
</h3>
<p>
<label>Any Suggestions/ Comments:</label>
<textarea name="comment"></textarea>
</h3>
<input type="submit" value="submit">
</form>
<div id="formResult"></div>
</body>
</html>
In formProcess.php
<h1>Here is the information submitted by you:</h1>
<h3>Name: <b><?php echo $_POST["name"] ?? ''; ?></b></h3>
<h3>gender: <b><?php echo $_POST["gender"] ?? ''; ?></b></h3>
<h3>Favorite Color: <b><?php echo $_POST["color"] ?? ''; ?></b></h3>
<h3>Hobbies: <b><?php if(isset($_POST["hobbies"])){ echo implode(", ", $_POST["hobbies"]); } ?></b></h3>
<h3>Comment: <b><?php echo $_POST["comment"] ?? ''; ?></b></h3>
Output:
On entering the details here:
On clicking on Submit:
We have seen here that every time a post method will send some data to other files specified, and some examples here shown are also retrieving the posted data to the user back.
GET method is used to get the data from any URL specified.
Conclusion
We have seen how it works, and its syntax in various forms explained all the required and optional parameters above. Examples solved here will give you an overview of how it is used to send the data to any of the files specified. A good example of Submitting a Form data is shown, which sends its data to a php file and displays the data sent to the file.
Recommended Articles
This is a guide to jQuery post. Here we discuss the introduction to jQuery post along with examples for better understanding. You may also have a look at the following articles to learn more –