Skip to main content

Use jQuery To Submit Form To PHP/MySQL

  1. <div class="container">  
  2. <form id="submit" method="post">  
  3. <fieldset>  
  4. <legend>Enter Information</legend>  
  5.   
  6.             <label for="fname">Client First Name:</label>  
  7. <input id="fname" class="text" name="fname" size="20" type="text">  
  8.   
  9.             <label for="lname">Client Last Name:</label>  
  10. <input id="lname" class="text" name="lname" size="20" type="text">  
  11.   
  12.             <button class="button positive"> <img src="../images/icons/tick.png" alt=""> Add Client </button>  
  13. </fieldset>  
  14. </form>  
  15. <div class="success" style="display: none;">Client has been added.</div>  
  16. </div> 
  1. $(document).ready(function(){  
  2.     $("form#submit").submit(function() {  
  3.     // we want to store the values from the form input box, then send via ajax below  
  4.     var fname     = $('#fname').attr('value');  
  5.     var lname     = $('#lname').attr('value');  
  6.         $.ajax({  
  7.             type: "POST",  
  8.             url: "ajax.php",  
  9.             data: "fname="+ fname +"& lname="+ lname,  
  10.             success: function(){  
  11.                 $('form#submit').hide(function(){$('div.success').fadeIn();});  
  12.   
  13.             }  
  14.         });  
  15.     return false;  
  16.     });  
  17. }); 
  1. success: function(){  
  2.      $('form#submit').hide(function(){$('div.success').fadeIn();});  

  1. <?php  
  2.   
  3.     include ("../../inc/config.inc.php");  
  4.   
  5.     // CLIENT INFORMATION  
  6.     $fname        = htmlspecialchars(trim($_POST['fname']));  
  7.     $lname        = htmlspecialchars(trim($_POST['lname']));  
  8.   
  9.     $addClient  = "INSERT INTO clients (fname,lname) VALUES ('$fname','$lname')";  
  10.     mysql_query($addClientor die(mysql_error());  
  11.   
  12. ?>