Updated March 29, 2023
Introduction to JQuery Ajax Post
jQuery Ajax Post method sends asynchronous HTTP POST requests to the server to load data from the server. Ajax ( Asynchronous JavaScript And XML) refers to exchanging data with the server and updating the part of web pages without reloading the whole page. jQuery offers various methods to implement AJAX functionality. This method is one of them using which we can directly load data from the server on the web page by sending an HTTP POST request. Shortcut for the ajax() post method is $.post().
Syntax
$.post(url, [data], [callback(data, status, xhr)], [type])
Where,
url refers to the URL to which a request is sent to fetch data.
Data is an optional parameter and represents the json data that is sent to the server along with the request.
Callback (data, status,xhr) is also an optional parameter that refers to the function to be executed after the request is sent and the data is loaded successfully.
- data refers to the data contained in the response from the server
- status refers to the status of the request, such as success, error, timeout, not modified, etc.
- xhr refers to XMLHttpRequest object.
type is also an optional parameter that specifies the type of data which will be returned as a response from the server, such as json, jsonp, xml, html, script, and text.
How does jQuery Ajax Post Work?
jQuery Ajax Post method, or shorthand, $.post() method makes asynchronous requests to the web server using the HTTP POST method and loads data from the server as the response in the form of HTML, XML, JSON, etc.
Given below is the sample of a POST request sent to the server using ajax
$.ajax({
type: "POST",
url: url,
data: data,
dataType: ‘json’,
success: function(){
//success code here
},
error: function(){
//error code here
}
});
In the above format, the first parameter is “type,” which represents the type of call to the server; here, it is POST that sends an HTTP POST request to the server.
The second parameter is url to which we want to send an HTTP POST request to submit our data.
The third parameter is data that is to be submitted to the server through the POST request.
The fourth parameter is the success callback function which is called only if the request is successful and the server returns the response. In turn, the callback function has three parameters: data, status, and jqXHR, where the data parameter contains the response from the server.
An error callback gets invoked in case the AJAX POST request fails and throws an error.
The last parameter is dataType which is here specified as JSON. This means, once the POST request succeeds, the servers return the response in JSON format.
Examples for jQuery Ajax Post
Let us now see how to post data and get the response from the server using the post() method.
Example #1
Given below is an example that implements the jQuery Ajax Post method.
Code:
<html>
<head>
<title>jQuery Ajax POST Example</title>
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/css/bootstrap.min.css"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.2/js/bootstrap.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function () {
$(".bin").click(function () {
var datastring = $("#Form").serialize();
$.ajax({
type: "POST",
url: "https://httpbin.org/post",
data: datastring,
dataType: "json",
success: function (data) {
var obj = JSON.stringify(data);
$(".result").append(
'</textarea></li><li class="list-group-item active">Result</li><li class="list-group-item">Name: ' +
data["form"]["name"] +
'</li><li class="list-group-item">Email: ' +
data["form"]["email"] +
'</li><li class="list-group-item">Gender: ' +
data["form"]["multiple"] +
'</li><li class="list-group-item">Comments: ' +
data["form"]["text"] +
"</li></ul></div>"
);
},
error: function () {
$(".result").append("Error occured");
},
});
});
});
</script>
<style>
#divstyle {
width: 600px;
height: 550px;
padding-top: 20px;
padding-left: 5px;
font-size: 16px;
text-align: center;
color: maroon;
background-color: cadetblue;
}
</style>
</head>
<body>
<div id="divstyle">
<div class="container text-center">
<form id="Form">
<div class="form-group">
<label for="FormControlInput">Enter your name</label>
<input
type="name"
name="name"
class="form-control"
id="FormControlInput"
/>
</div>
<div class="form-group">
<label for="FormControlInput">Enter your email id</label>
<input
type="email"
name="email"
class="form-control"
id="FormControlInput"
/>
</div>
<div class="form-group">
<label for="FormControlInput">Enter your gender</label>
<select
multiple
name="multiple"
class="form-control"
id="FormControlSelect"
>
<option selected>Male</option>
<option>Female</option>
</select>
</div>
<div class="form-group">
<label for="FormControlInput">Enter your comments</label>
<textarea
name="text"
class="form-control"
id="FormControlTextarea"
rows="3"
></textarea>
</div>
<button type="button" class="btn btn-primary bin">Submit</button>
</form>
<br />
<div class="result"></div>
</div>
</div>
</body>
</html>
Output:
- The below screen displays when the above code gets executed.
- In this example, form data is posted to the server using an AJAX POST request, and the result is put into a div.
- The response returned is in JSON format as specified in dataType of the ajax call.
Example #2
Here is another example that implements the jQuery Ajax Post method
Code:
<!DOCTYPE html>
<html>
<head>
<script
type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"
></script>
<script type="text/javascript">
jQuery("document").ready(function () {
jQuery(".FormBox1").submit(function () {
event.preventDefault();
var fields = jQuery("input", this).serializeArray();
jQuery("#response").empty();
jQuery.each(fields, function (i, field) {
jQuery("#response").append(field.value + " ");
});
jQuery
.ajax({
method: "POST",
url: "sampleData.php",
data: fields,
})
.done(function (message) {
console.log("Data Saved: " + message);
});
});
});
</script>
<style>
#response{
color: blue;
}
#divstyle {
width: 350px;
height: 450px;
padding-top: 20px;
font-size: 18px;
text-align: center;
color: maroon;
background-color: cadetblue;
}
</style>
</head>
<body>
<div id ="divstyle">
<div class="container">
<form class="FormBox1">
<dl>
<dd><input type="hidden" name="name" value="<?php echo ($_SESSION['myname']) ?>">
<input type="hidden" name="approve" value="Hi">
<input type="hidden" name="id" value="<?php echo $_GET['id'];?>"/>
<dt><p>Enter your name</p>
<dd><input type="text" name="Fullname" id="text">
<dt><p>Enter your gender</p>
<dd><select name="gender" id="text">
<option value="0">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<dt><p>Enter your DOB</p>
<dd><input type="date" name="start" id="text">
<dt><p>Enter your DOJ</p>
<dd><input type="date" name="end" id="text"><hr>
<dt><button type="submit" name="submit" class="btn" >Next</button><span id="response"></span></td>
</dl>
</div>
</div>
</body>
</html>
Output
- The below screen displays when the above code gets executed.
- On clicking the button “Next,” the form data gets posted using the Ajax Post method, and the below screen displays.
Conclusion
- In this article, we discussed the jQuery implementation of Ajax Post
- Ajax refers to exchanging data with a web server and hence enables web pages to be updated asynchronously.
- Ajax Post refers to sending synchronous HTTP POST requests to the webserver to load data from the server.
Recommended Articles
This is a guide to JQuery Ajax Post. Here we discuss How does jQuery Ajax Post Work and Examples along with the codes and Outputs. You may also have a look at the following articles to learn more –