Sunday, January 9, 2011

Submit Form with JQuery , PHP, HTML,MYSQL

Let us understand with a simple example of how to submit a form to a database with JQuery, PHP, HTML, MySql.

This is a direct working code with explanation given whereever required.


<div class="container">  
<form id="submit" method="post">  
<fieldset>  
              <legend>Enter Employee Information</legend>  
  
              <label for="fname">Employee First Name:</label>  
           <input id="fname" class="text" name="fname" size="20" type="text">  
  
              <label for="lname">Employee Last Name:</label>  
              <input id="lname" class="text" name="lname" size="20" type="text">  
  
            <button class="button positive"> <img src="../images/icons/somepic.png" alt=""> 
                 Add Employee </button>  
  </fieldset>  
</form>  
<div class="success" style="display:none;">Employee has been added.</div>  
</div>  


// It is relatively easy to make ajax calls with jquery. we need to pass type( GET or POST),
// URL ( of the destination), data,  success( what to be done post successful execution).

$(document).ready(function(){  
    $("form#submit").submit(function() {  
    // we want to store the values from the form input box, then send via ajax below

    var fname     = $('#fname').attr('value'); 

// We are storing it in the variable called “fname” and we are taking it from the input
       //  field with the id of “fname” and the “.attr(‘value’) tells jQuery to take the value from
       // the attribute of the value from the input field

    var lname     = $('#lname').attr('value');  
        $.ajax({  
            type: "POST",  
            url: "ajaxcalls.php",  
            data: "fname="+ fname +"& lname="+ lname,  
            success: function(){  
                $('form#submit').hide(function(){$('div.success').fadeIn();});  
  
            }  
        });  
    return false;  
    });  
});  



Add this in ajaxcalls.php File:



<?php  
  
    include ("../../inc/config.inc.php");  
  
    // Employee INFORMATION  
    $fname        = htmlspecialchars(trim($_POST['fname']));  
    $lname        = htmlspecialchars(trim($_POST['lname']));  
  
    $addClient  = "INSERT INTO Employees (fname,lname) VALUES ('$fname','$lname')";  
    mysql_query($addClient) or die(mysql_error());  
  
?>  


Hope you like it.

1 comment:

  1. Thanks for sharing your info. I really appreciate your efforts and I will be waiting for your further write ups thanks once again.

    ReplyDelete

subversion video