20 September 2011

How to submit a form and save it into database using AJAX?


Few days ago, I was looking for some way, so that  I can submit my web form using AJAX and show the results on the same page without loading the entire page again

I found many long scripts on Google, but most of them were crap and useful ones were not complete, So  I combined all those useful ones to get a simple and easy script

In this tutorial I am assuming that you are aware of basic HTML required for writing web form. I will write some scripts in JQuery and PHP.

Now Let us start with some PHP coding

First of all we will create one new file named “process.php” that will save my data into database.
Please see the explanation of  code in comments written below along with code


<?php

// First I will make the connection with database

$hostname = ‘localhost”;
$username = “root”;
$pass = “”;

$link = mysql_connect($hostname, $username, $pass);

// Now we will select our database
$con = mysql_select_db($dbname, $link);

// Now we will retrieve post data which you had submitted

$name = $_POST[‘name’];
$phone_no = $_POST[‘phone_no’];

// Now write simple query to insert data into database

$query = “insert into registration (name,  phone_no) values(‘$name’,  ‘$phone_no’)”;

//Now execute this query return the response
if(mysql_query($query)){
echo “Data Submitted”;
} else {
echo “Data not submitted”;
}

// With this we are done with our PHP script
?>


Now its time to write our Jquery Scripts, Please read the comments along with script for explanation

<script type = “text/javascript”>
            // When you will click buton then control will come here
$("#addMessage").click(function(e){
                                    // Prevent default execution of script
e.preventDefault();

/* This line is very important , here you serialized
 the entire form data and then pass it to process.php */
                                   
var data = $('#MeetingMessageAddForm').serialize();
                                   
// Here we start with ajax script it has its own parameters,
you can set it according to your requirement , for eg type
may be GET , url where you want to pass data */

$.ajax({
                                                type: "POST",
                                                url: "/process.php",
                                                dataType: "text",
                                                data: data,
                                                success:function(data){
                                                // here you will write response in your HTML form 
                                                            $("#message").html(data);
}
                                    });
                       
});
</script> 
With this we are done, if you have any confusion at any point then feel free to comment , I will be happy to answer my viewers