Insert Data using jQuery Ajax in PHP

 

Introduction

In this article we will see step by step to post the data and to insert into mysql database without refreshing the current page using php scripting and jQuery ajax code.The jQuery library has a full suite of Ajax capabilities inbuilt jQuery ajax function which allows load data or to post data/ insert data without any page load/refresh.

Why we need jQuery Ajax

 

 

When we send a page without using ajax to the server it post backs form element data, images, hidden fields cookie information to the server and server make the page and sends the same information back to the browser. So there is a unnecessary data is transferred between client and server and whole page is posted and refreshed and even for the small amount of data whole page is posted and refreshed. Due to this it makes user experience very difficult and server is overloaded with unnecessary process/pings.

 

Ajax is client side technologies which provides asynchronous process means data will be posted to server in asynchronous way with minimal data transfer or lets say page will not be refreshed when a data is transferred without a page load/page refresh data is posted to the server in an asynchronous mode and by this server is not overloaded with unnecessary load. We should use jQuery ajax when we want to maintain user friendly experience and to minimize load on the server.

Step 1 : Create a Simple HTML Form

First step is to create a simple HTML form with necessary fields. In this step we will create simple contact form with fields like Name, Email, Contact and Message and two tags one div tag for register form and second div tag to display success message if data inserted properly.

 

<div id="formregister">	

  <form id="frmRegister" style="margin: 0; padding: 0; float: left;" enctype="multipart/form-data" method="post">	
  
  <p class="qc-errmsg" style="display: none;">&nbsp;</p>
  <table style="border-collapse: collapse; font: 12px Verdana, Arial, Helvetica, sans-serif;" border="1" cellspacing="1" cellpadding="5">
  
  <tbody><tr>
  <td align="left"> Full Name : </td>
  <td> <input name="fullname" size="40" type="text" /></td>
  </tr>
  
  <tr>
  <td align="left"> Email : </td>
  <td> <input name="email" size="40" type="text" /></td>
  </tr>
  
  <tr>
  <td align="left"> Contact No : </td>
  <td> <input name="contact" size="40" type="text" /></td>
  </tr>
  
  <tr>
  <td align="left"> Message : </td>
  <td> <textarea cols="40" rows="8" name="message"></textarea></td>
  </tr>
  
  <tr>
  <td colspan="2" align="left"> <input name="Sub" type="submit" value="Submit" /> </td>
  </tr>
  
  </tbody></table>
  </form>
 
</div>	

<div id="successfulpost" style="font: bold 12px Verdana, Arial, Helvetica, sans-serif; color: #ff0000; display: none;">
<p class="jst-txt"><span>Thank you,</span> for showing your Interest !!</p>
<p class="jst-txt">Our property advisor shall get in touch with you very shortly..</p>
</div> 

As you see from our above code that we have created simple contact form with form id "frmRegister" and contact form enclose in div tag called "formregister" and second div tag "successfulpost" is to display successful message if jQuery ajax function returned back success message if posted data successfully inserted into database and display div qc-errmsg if jQuery ajax function returns any error message if any error occured in the server side.

Kindly Note : I'm using form id and div id names in my jQuery ajax functions. so while choosing id names please choose unique name only otherwise jQuery function will not work properly.

Step 2 : Create Form Validation using Javascript Function

In the webform or in any website, when there is an user input form or a form where you are collecting data from your customers it is compulsary to keep validations. Validation ensures that all data posted will be in a property format and also you can make some fields mandatory so that form will not be posted unless and until it has proper format data.

In this scenario we did the basic validations only because just to ensure that form is posted with some data. so we have did only basic validation as checking if the textbox is empty or not and an email validation. In the further upcoming article we will try to cover a complete article on Javascript Validations.

So let's create a script tag in the head section of the HTML file to write a Javascript function.


<script type="text/javascript">

function Form_Validator(theForm) {


    if (theForm.fullname.value == "") {
	alert("Please Enter Your Full Name.");
	theForm.fullname.focus();
	return (false);
    }
	
	
    if (theForm.email.value == "") {
	alert("Please Enter Your Email Address.");
	theForm.email.focus();
	return (false);
    }
    
    if  (theForm.email.value != "") {   
    var eresult
    var str=theForm.email.value
    var filter=/^([\\w-]+(?:\\.[\\w-]+)*)@((?:[\\w-]+\\.)*\\w[\\w-]{0,66})\\.([a-z]{2,6}(?:\\.[a-z]{2})?)$/i
	if (!filter.test(str)) {
	    alert("Please enter a valid Email address!")
	    theForm.email.focus();
	    eresult=false;
	    return (eresult);
	}	
    }   
    
    if (theForm.contact.value == "") {
	alert("Please Enter Contact Number.");
	theForm.contact.focus();
	return (false);
    }
	
	
    if (theForm.message.value == "") {
	alert("Please write your message/comments in message box.");
	theForm.message.focus();
	return (false);
    }
    
  return true;
  
}

</script>


We have created the form validation function because just to ensure that we have all input field filled properly with some data and there should not be any empty data posted to mysql database.

Step 3 : Reference/Download jQuery library

You need to first reference jQuery library before using any jQuery functions and methods.

There are two ways to use jQuery library.

1 : You can directly download jQuery mew released version library file from http://jquery.com/download/ website and save it in your server and use that path to reference jQuery library in html file using script tag.
2 : It is a simplest method. You just need to copy the url of jQuery library (latest version) from jQuery CDN (.i.e from http://code.jquery.com/) and use that url in the script tag of the html page as shown below.

<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>

Step 4 : Create jQuery Ajax Function

In the previous step we have created the validation function. Now in this step we will create a new function which will have jQuery Ajax functions and methods. So let's create a new function called "submitAndsaveData" with input of form object.

<script type="text/javascript">
function submitAndsaveData(frmQC) {
//some code
}
</script>

In the next line of code we will call our validation function "Form_Validator()" in the "IF-Statement". So before submitting form to ajax methods we will first check all input field filled properly.

<script type="text/javascript">
function submitAndsaveData(frmQC) {

	if(Form_Validator(frmQC)) {
		
		///some code;
            }
	return false; 
}
</script>

jQuery.Ajax

Now in the next step we will call our jQuery ajax function. jQuery Ajax function is the extended version of JavaScript AJAX methods and jQuery library has a full suite of Ajax capabilities which allow us to load data or post data from the server without a browser page refresh and jQuery.ajax performs an asynchronous http ajax request and provide more flexible way to post or to get data from the server.

jQuery.ajax parameters

jQuery.ajax({url, async, cache, data, type, [callback]});

URL : Custom String url or page url where data to be posted or fetched.
async : Boolean If set to "True" then all requests are sent asynchronously.
cache : Boolean by default "True". if set to "false" it will force requested pages not to be cached by the browser.
data : Form Data to be sent to the server.
type : Type of data sent to the server either via "POST" or "GET" method.
callback : Callback function to be called if the request succeeds and to load data returned from the server.

Now let just set the values to the ajax parameters.

url : "savedata.php",
async : true,
cache : false,
data : $('#frmRegister').serialize(),
type : 'post'
callback : success

Note : '#frmRegister' is the html form id. So we are using form id to post all input elements inside that form id to the server in a serialize way.

<script type="text/javascript">

function submitAndsaveData(frmQC) { 
   
    if(Form_Validator(frmQC)) {	
		    
	$.ajax({
	    url: '/savedata.php',
	    async: true,
	    cache: false,
	    data: $('#frmRegister').serialize(),
	    type: 'post',			
	    success: function (data) {
		    data=data.replace(/\\s+/g,"");
		    if(data == "true"){
		    //alert("success");
			    $('.qc-errmsg').empty();
			    $('#formregister').hide();	
			    $('#frmRegister').hide();	
			    $('div#successfulpost').fadeIn();			
		    }
		    else {
		         //alert(data+" failed");
			    $('#frmRegister').show(function(){					
			    $('.qc-errmsg').html(data);
			    $('.qc-errmsg').fadeIn(500);
			    });
		    }
	    },
	    error : function(XMLHttpRequest, textStatus, errorThrown) {
		    alert(textStatus);
	    }
	});
	
	return false;
    }
    return false;    
}

</script>

As you see from our above jQuery.ajax function that we have called our jQuery.ajax successfully in the "submitAndsaveData()" function and in the callback function we called success function with data fetched from url : savedata.php. If data is true (If inserted properly in mysql database) then we fadein() the div "successfulpost" and hidden the div "formregister" and form "frmRegister". if data is failed (not inserted in mysql database or if any error occured) then we have displayed the error message in div qc-errmg.

Step 5 : Create Server Side PHP Page

In this step we will create a new server side php page called "savedata.php" because in the jQuery.ajax url parameter we gave url name as "/savedata.php" or "http://www.your-domain.com/savedata.php". so we will create a new php page with name called "savedata.php".

What "savedata.php" consist of

In this page we will first create a mysql connection

MYSQL Connection

<?php
/**********Settings****************/
$host="localhost";
$dbname="onlinebuff";
$user="root";
$pass="";
/**********Settings****************/


$conn=mysql_connect($host,$user,$pass);

if($conn)
{
$db_selected = mysql_select_db($dbname, $conn);
if (!$db_selected) {
    die ('Can\\'t use foo : ' . mysql_error());
}
}
else
{
    die('Not connected : ' . mysql_error());
}
?>

Next we will create http form posted field variables.

<?php

if(!empty($_POST["fullname"])){
$fullname = $_POST["fullname"];


if(!empty($_POST["email"])){
$email = $_POST["email"];
}

if(!empty($_POST["contact"])){
$contact = $_POST["contact"];
}

if(!empty($_POST["message"])){
$message = $_POST["message"];
}

?>

Finally Insert into Mysql Database using insert query

<?php

$todate = date("Y-m-d");

$query_customers = "INSERT INTO 'customers' ('customer_name','customer_email','customer_contact','message','posteddate') VALUES ('" .$fullname. "','" .$email. "','" .$contact. "','" .$message. "','" .$todate. "')";

$sql_customers = mysql_query($query_customers) or die(mysql_error());

if(mysql_affected_rows() > 0){
echo "true";
}else{
echo "MYSQL Error : ".die(mysql_error());
}

?>

As you see from above the code that if data inserted into mysql database table successfully then we have display message as "true" else "MYSQL Error".

If you remember in the ajax callback success function there we have declared if data is "TRUE" then display successful message else shown an error message. So thatswhy in the server side php page we have displayed message as "TRUE" if inserted successfully else "MYSQL ERROR MESSAGE".

 success: function (data) {
		    data=data.replace(/\s+/g,"");
		   if(data == "true"){
		 
			    $('.qc-errmsg').empty();
				$('#formregister').hide();	
			    $('#frmRegister').hide();	
			    $('div#successfulpost').fadeIn();			
		    }
		    else {
		         //alert(data+" failed");
			    $('#frmRegister').show(function(){					
			    $('.qc-errmsg').html(data);
			    $('.qc-errmsg').fadeIn(500);
			    });
		    }
	    }

So hey friends hope you like this article. If you have any doubts in jQuery Ajax functions or implementation of Ajax in your website kindly feel free to ask me through your comments. The more the knowledge we share the more we grow so feel free ask me any doubts on jQuery Ajax. Help me to grow kindly share this article in your  social media networks. Thanks.

 

 

:: SHARE THIS POST ::

        
 

More PHP Articles To Read Next:

 
Apr
18
2014

Step by step to upload a file to ftp server using php code

CLICK TO READ FULL ARTICLE

Views - 15708 |Category - PHP

Apr
06
2014

Step by step to upload an image and store in database using php

CLICK TO READ FULL ARTICLE

Views - 198539 |Category - PHP

May
01
2013

How to get Date and Time using PHP

CLICK TO READ FULL ARTICLE

Views - 13607 |Category - PHP

Apr
28
2013

What is PHP with a simple example using PHP

CLICK TO READ FULL ARTICLE

Views - 11743 |Category - PHP

 
Author: Gurunatha Dogi
is a software engineer by profession and founder of Onlinebuff.com, Onlinebuff is a tech blog which covers topics on .NET Fundamentals, Csharp, Asp.Net, PHP, MYSQL, SQL Server, Cell Phones and lots more. Follow me @ and twitter.
Leave a Comment......

All fields marked with * are mandatory

rr1uv

 

 
Comments

Posted by Rajesh g vaghasiya on 2014-12-09

hello I am download this code. but not work. How can i Find Error or u help me for this code.

Posted by Nazri on 2014-08-21

sir, could u please email the full downloaded code with exactly filename to save for every code you post? TQ

Posted by Kate on 2014-08-15

Is there any possibility that you could look ar my code and see if maybe you find some mistake because I'm following your guidelines precisely and even the validation is not working?

Posted by Kate on 2014-08-15

Is there any possibility that you could look ar my code and see if maybe you find some mistake because I'm following your guidelines precisely and even the validation is not working?

Posted by Grant on 2014-08-12

Your script works great. But I do have a problem that I am hoping you can help with. I have two scripts. One is for login, the other for register. I can login using the code above as guidance. It works. Then I click on register, which is almost the exact same code but it doesn't work. I know the issue is that in the JS login script, I have data defined, and then in the register script I have data defined. I am using the cache=false. If I clear the cache, the scripts work, but obviously I can't have users doing that. Do you have any suggestions as to resolve this. Thanks, Grant

Posted by Grant on 2014-08-12

Your script works great. But I do have a problem that I am hoping you can help with. I have two scripts. One is for login, the other for register. I can login using the code above as guidance. It works. Then I click on register, which is almost the exact same code but it doesn't work. I know the issue is that in the JS login script, I have data defined, and then in the register script I have data defined. I am using the cache=false. If I clear the cache, the scripts work, but obviously I can't have users doing that. Do you have any suggestions as to resolve this. Thanks, Grant

Posted by Mahesh Kumar on 2014-08-04

it works...thanks

Posted by Patrick on 2014-07-07

plz sir, how can I learn more about programming, I would like to start from the beginning plz sir if there's anything u can do to assist let me know God bless u sir

Posted by Raj on 2014-07-04

i like your code . and it is very usefull to me. but i want code in which first i insert data and than on same page i display that all records which is in database using ajax jquery. please help me.