May 22, 2013

php form with ajax post

You have a form in a page and  if you want to submit that form from the same page itself and display the result there itself without moving from the page then it is the post


There are two php files one is index.php and the functions.php.

index.php
 <!DOCTYPE html>  
 <head>  
  <title>form</title>  
  <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>  
  <script type="text/javascript" src="http://code.jquery.com/ui/1.10.2/jquery-ui.min.js"></script>  
 </head>  
 <body>  
   <form>  
    <input type="text" name="input_box" id="input_box" style="width:200px;" value="" />  
    <input type="button" class="submit_button" value="submit"/>  
   </form>  
   <script>  
    $('.submit_button').click(function() {  
     var value = $("#input_box").val(); // # represents id.  
     $.ajax({  
       type:'POST',  
       url: 'functions.php',  
       data: { info : value },  
       dataType: 'json',  
       cache: false,  
       success: function ( data ) {  
           $(#result).text( data.q );  //check data.suc == 'y' if required
       },  
       error: function() {  
        alert('error');  
       }  
    });  
   }  
   </script>  
  <div id="result"></div>  
 </body>  
 </html>  

Now functions.php

 <?php  
  if ( isset ( $_POST['value'] ) )  
  {   
     $value = $_POST['value'];  
     print json_encode ( array ('q' => $value, 'suc' => 'y') );  
  }  
 ?>  

This is a very simple php script for which apache and php is required. Setup them in ubuntu, configure them and then copy the above two files in /var/www/ and then go to localhost/index.php. It will update the div 'result' with the value in the text box. But not directly but with a post to the server and return.

For Web Developer

  open -a "Google Chrome" --args --disable-web-security