Do you want to be a good Web Developer?

Enter Your Email To Get Our Exclusive Tutorials
And Offer Right In Your Email

Join TalkersCode Community And Recieve Exclusive Tutorials
On Web Development Right Via Email.

Submit The Form Without Page Refresh Using Ajax And jQuery.

Saturday, Dec 24, 2016

Tags:- Ajax JavaScript jQuery PHP


In this tutorial we will teach you how to submit the form without page refresh and then insert the data into database using Ajax and jQuery.You only need to download jQuery to submit the form without page refresh.You may also like jQuery form validation.


Submit Form without page refresh


To Submit the form without page refresh it takes only two steps:-

  1. Make a HTML form to submit the data
  2. Connect to the database and store data


Step 1.Make a HTML form to submit the data

We make a HTML form with post method and save it with a name senddata.html

<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">

function submitdata()
{
 var name=document.getElementById( "name_of_user" );
 var age=document.getElementById( "age_of_user" );
 var course=document.getElementById( "course_of_user" );

 $.ajax({
  type: 'post',
  url: 'insertdata.php',
  data: {
   user_name:name,
   user_age:age,
   user_course:course
  },
  success: function (response) {
   $('#success__para').html("You data will be saved");
  }
 });
	
 return false;
}

</script>

</head>
<body>
		
<form method="POST" onsubmit="return submitdata();">
 <input type="text" name="username" id="name_of_user">
 <input type="text" name="userage" id="age_of_user">
 <input type="text" name="usercourse" id="course_of_user">
 <input type="submit" name="submit_form" value="Submit">
</form>

<p id="success_para" ></p>

</body>
</html>

You can do validation to make your code more secure or you can view our How to do validation before and after submitting the form tutorial.



Step 2.Connect To The Database and Store Data

In this step we get all the data which get get from senddata.html page and store them in database.

// insertdata.php

<?php

if( isset( $_POST['user_name'] ) )
{

$name = $_POST['user_name'];
$age = $_POST['user_age'];
$course = $_POST['user_course'];

$host = 'localhost';
$user = 'root';
$pass = ' ';

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

mysql_select_db('demo');

$insertdata=" INSERT INTO user_info VALUES( '$name','$age','$course' ) ";
mysql_query($insertdata);

}
?>


That's all, this is how to submit the form without page refresh. You can customize this code further as per your requirement. And please feel free to give comments on this tutorial.

Join Us With Our 21000+ Subscribers And Get Our Latest Tutorials Update Via Email