Monday, June 15, 2015

Submit form without a page refresh in PHP/Jquery

In this post, we will explain about submit the form without a page refresh using jquery and PHP.

STEP 1:
I'm using bootstrap front-end framework. the first thing we need to do building proper HTML form using bootstrap classes.

Make jquery-post folder inside create a file index.php and use this below HTML markup.
 

Submit A form Without page Refresh




Using this code, Page should be looks like this.
step 2 create the code.js file and I'm using jquery library for post form include jquery library and code.js file in index.php at the bottom.
e.preventDefault we use e.preventDefault() method for default action of the event will not be triggered.
$.ajax is a jquery method that method post a form we need to define type is a post or get, URL where we want to submit a form after success callback function is executed.
$(document).ready(function(){
 $('#form1').submit(function(e){
  e.preventDefault();
  var formdata = $(this).serialize();
  $.ajax({
   type:'POST',
   url:$(this).attr('action'),
   data:formdata,
   success:function(data){
    console.log(data);
   }
  
  })
 
 });
});

Step 3 When we submit a form, Success callback is executed. The data arguments returned from the server, formatted according to the Type Parameter.first we check what data parameter return using console.log() method.I'm using google chrome, view inspect element click console tab.

Now in the final step, we will insert data MYSQL, Using database library, Create database 'jquery-post', create table 'records' with 4 fields.
1 - id int(11),
2 - name varchar(50),
3 - email varchar(100),
4 - msg varchar(255)
In records.php file paste this below code.
<?php 

if(isset($_POST)){
 //database connection variables
 $username = "root"; 
    $password = ""; 
    $host = "localhost"; 
    $dbname = "jquery-post"; 
  
 //create new instance DB Mysqlidb
 $db = new Mysqlidb ($host, $username, $password, $dbname);
 $data = array(
  'name' => $_POST['name'],
  'email' => $_POST['email'],
  'msg' => $_POST['msg'],  
 );
 //using insert method 
 $db->insert('records',$data);

}

?>

0 comments:

Post a Comment