jQuery $.post() method is used to request data from a webpage and to display the returned result (sent from requested page) on to that webpage from where the request has been sent without page refresh.
$.post() method sends request along with some data using an HTTP POST request.
Under this, a request is send to a webpage (here it is jquery_post.php) from another page (say jquery_send.php) using syntax :
Syntax:
$.post( URL, data, callback);
Parameters:
URL
The URL parameter is defined for the URL of requested page which may communicate with database to return results.
$.post("jquery_post.php",data,callback);
data
The data parameter is defined to send some data along with the request.
,{ // Data Sending With Request To Server
name:vname,
email:vemail
}
callback
The callback parameter is defined for a function to be executed if the request gets succeeded. This contains two sub parameters , the first one holds the returned data from the requested page and second one holds the status of the request.
,function(response,status){ // Required Callback Function
//"response" receives - whatever written in echo of above PHP script.
alert("*----Received Data----*
Response : " + response+"
Status : " + status);
}
Note : Both ‘ data ‘ and ‘ callback ‘ parameters are optional parameters, whereas URL is mandatory for $.post() method.
Below is our complete code with download and live demo option
Example:
The following example uses the $.post() method to send some data along with the request.
This is jquery_send.php page that contains jQuery $.post() method which can be implemented as given below:
$(document).ready(function(){
$("#btn").click(function(){
var vname = $("#name").val();
var vemail = $("#email").val();
if(vname=='' && vemail=='')
{
alert("Please fill out the form");
}
else if(vname=='' && vemail!==''){alert('Name field is required')}
else if(vemail=='' && vname!==''){alert('Email field is required')}
else{
$.post("jquery_post.php", //Required URL of the page on server
{ // Data Sending With Request To Server
name:vname,
email:vemail
},
function(response,status){ // Required Callback Function
alert("*----Received Data----*
Response : " + response+"
Status : " + status);//"response" receives - whatever written in echo of above PHP script.
$("#form")[0].reset();
});
}
});
});