Insert data in mysql with help of php, jquery & ajax

There are number of people who are searching that how to insert data in database with help of Php, Jquery and Ajax.If you are also searching this then here is your answer.Here i have shared some knowledge about this.I have also created a example file with this tutorial which you can download.

Note !   If you doesn't find the file then feel free to email us, We will provide you soon.

1. Create Database where you will store the information.
2. Create HTML form where user will enter data. 
3. Create your js script for data insertoin via jquery & ajax.

I am using bootstrap classes and jquery-1.11.2 version for my ease.You can change this as per your convenience.I will explain you step by step.

Create your index.php file in which you make form like below:

After that create the most important custom.js file where you will get all form date and send them to php file with the help of ajax.In this file the following code will be added.

 // When click on submit button
  // Get the all the form values
  // I am getting here single-single value from input with the help of input's ID
  // First i will check in my console window that value is coming or not, You can use developer tool in firefox and chrome.
  // Here i will check that password is match or not
  if($_pass=='' || $_pass!=$_conpass){
   $(".loading").text('Password empty or doesn\'t match');
   return false;
   // Here i have used $.ajax method you can also use $.post, $.json or $.get method
    beforeSend:function(){ //this callback function is used before send request to server. 
      $(".loading").text('Your data has been successfully added').fadeOut(3000);
      // Clear the value of form
  console.log($_name); //this is just for testing purpose.

Note! please include higher version of jquery because i have used $ sign instead of var for declaring variable.

Note! Another important the ajax url is defined in "index.php" file, the first file of this tutorial.

Now create another important file which is "ajax.php" for sending data in mysql database.

// Database Configuration
 mysql_connect("localhost","root","") or die (mysql_error());
 mysql_select_db("jquery-ajax") or die (mysql_error());

  $action(); //With this technique we can run our function.

 // Create function add user in database.
 function add_user(){
  $res=new stdClass(); // In php stdClass is standard class for creating object.
  // Insert into database
  $insertQuery=mysql_query("INSERT INTO users (name,username,email,pass) VALUES ('$_name','$_username','$_email','$_pass')");
  echo json_encode($res);
  // json_encode function is used for converting objects in json becuase in our custom.js dataType is json.

I hope you enjoy this tutorial.



Web Hosting