JQuery HTTP POST method of posting data

post(url,Data,Callback function, Data Type)

URL: The page (usually server side script like ASP, PHP, Perl etc .) to receive data
Data: Set of data in name value pairs
Callback function : Optional function to know the status and handle return data
Data Type : Type of data we are going to receive like json, XML, text, html , scripts
HTTP Post method is used to transfer user entered data to backend script and get the response. Get method also can be used in same way but there is a choice where we can use POST or GET method.

Let us start with some examples

Posting data without any return value

We will connect click event of a button with id = b1
$("#b1").click(function(event){
Inside this we will use POST method to send a form data to backend script. To keep the code simple we will only post data and will not expect any return data from backend script.

Demo of posting data ( without any return value )

To check the data at backed script you can write received data to a text file and read the same. In your demo script inside form-postck.php file the code is there to enter data inside test_file.txt file. The code to handle backend script is here.
$t1=$_POST['t1'];
$t2=$_POST['t2'];
$str =" Welcome  $t1 $t2";
echo $str;
In this case we are not sure of what has happened to our data. So better is to get a reply from backend script about the process.

Posting data by POST method and collecting return data

We will add a function to above code to collect the data and display the same inside a div layer.

The jQuery part is here.

<script>
   $(document).ready(function() {
      $("#b1").click(function(event){

$.post( "postck1.php", {"t1":$('#t1').val(),"t2":$('#t2').val()},function(return_data,status){
//$.post( "postck.php", $( "#f1" ).serialize(),function(return_data,status){
          $("#msg").html(return_data);
});     
  });
});
</script>

Demo of posting data ( without return string )

We have posted the data and got the return data from backend script. Our function

In above line you have seen how the data is posted as name value pair, we can create similar pair by using Serialize () function. We need not write each element of the form in name value format. Our Serialize() function will do that for us. This is useful when we have large number of form components to post data.

After posting the data to backend script using POST method, we can receive the return message ( from backend script ) and display the same inside our message layer. Here is the code for our backend script.
<?Php
$t1=$_POST['t1'];
$t2=$_POST['t2'];
$str =" Welcome  $t1 $t2";
  echo $str;
?>
The output of backend script is received by our jQuery variable return_data. The same value is displayed inside our message layer.
$("#msg").html(return_data);

Posting data and collecting return data in JSON format

In above example we have seen how our script receives message from backend script and display the same to the user. Here this is a single message ,however we many need different messages showing status of different form components and some return data. For such requirement the more practical way is to receive data from backend script in JSON format. We can receive large number of data including array as jSON string.

The backend script and JSON format

Our backend PHP script will collect the user entered data and validate the same. We have created an array to store validation status against each input filed. In this example we have used 2 elements but the array elements can be increased to check more elements.

Based on the validation checking we will be adding message to our variable $msg and the value of the variable $validation_status will change.

After all validations are completed we will create a JSON string format and return the same to our parent page ( jQuery code to handle ) Here is the backend PHP code.
<?Php
$t1=$_POST['t1'];
$t2=$_POST['t2'];

$elements=array("t1"=>'T',"t2"=>'T',"msg"=>'',"validation_status"=>'OK');
$validation_status='OK';
$db_status='OK';
$msg='';

if(strlen($t1) <1 ){
$elements[t1]='F';
$validation_status= "NOTOK";
$msg.= " Enter your first name ";
}
if(strlen($t2) <1 ){
$elements[t2]='F';
$validation_status= "NOTOK";
$msg.= " Enter your last name ";
}
$elements["msg"]=$msg;
$elements["validation_status"]=$validation_status;
echo json_encode($elements);
?>


Inside the POST function ( JQUERY file ) we used JSON as data type.

Instead of receiving one message as string we will receive an array of different values. One such value is return_data.validation_status , this value will be OK or NOTOK depending on the validation status we receive from backend script.

Here the requirement is user must enter both the names ( first and last name ) and if any one or both of them is missed then we must display the matching error message. In addition to that we will display the corresponding input field error status. To mark the corresponding input filed as error we will declare one style property and assign that to the respective elements.

For example if last name is not entered then last name filed will change the color ( by applying error property ) .

We will declare one style property like this.
<style>
.error{
         background-color: yellow;
         border-color: red;
}
</style>

Changing the input element style property

Based on the received JSON string from backend script , we will find out the data associated with form input elements. If the user has not entered the second name then return_data.t2 will be equal to 'F'. Here is the code to read the status and apply error property to the data element.
if(return_data.t1 =='F'){$("#t1").addClass('error');}
else{$("#t1").removeClass('error');}
if(return_data.t2 =='F'){$("#t2").addClass('error');}
else{$("#t2").removeClass('error');}

Decoding the JSON string and displaying messages.

In our POST method we have mentioned that incoming data type will be in JSON format. Hence we will receive data as JSON string so we need to decode the same. The return data will have several name value pairs and we will try to read them and based on the value respective action can be taken.

For example to know the validation status we will use return_data.validation_status. If it is equal to OK then we will display Welcome message otherwise we will display error message. Here is the example of it.
if(return_data.validation_status=="NOTOK"){
 $("#msg").html(return_data.msg);
}else{
 $("#msg").html("Welcome " + $('#t1').val() + $('#t2').val());
}
The full code is here

jQuery & HTML

<script>
$(document).ready(function() {
 $("#b1").click(function(event){

  $.post( "postck2.php", $( "#f1" ).serialize(),function(return_data,status){

  if(return_data.validation_status=="NOTOK"){
  $("#msg").html(return_data.msg);
  }else{
  $("#msg").html("Welcome " + $('#t1').val() + $('#t2').val());
  }

      if(return_data.t1 =='F'){$("#t1").addClass('error');}
      else{$("#t1").removeClass('error');}
      if(return_data.t2 =='F'){$("#t2").addClass('error');}
      else{$("#t2").removeClass('error');}

         
 },"json");    
 });
});
</script>
<table><form id=f1>
<tr><td>First Name</td><td><input type=text id="t1" name="t1"></td></tr>
<tr><td>Second Name</td><td><input type=text id="t2" name="t2"></td></tr>
<tr><td colspan=2><input type="button" id="b1" value="Submit"></td><td></td></tr>
</form>
</table>

      
<div id="msg" class="msg"></div>

STYLE

<style>
.error{
         background-color: yellow;
         border-color: red;
}
</style>

Demo of posting data ( Return data type : JSON )

Demo of displaying validation message using Bootstrap4 alert

HTTP GET method of posting data







Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here .







    Most Popular JQuery Scripts

    1

    Two dependant list boxes

    2

    Calendar with Date Selection

    3

    Data change by Slider

    4

    Show & Hide element


    JQuery Video Tutorials




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer