jQuery

Submit Form Without Page Refresh Using Ajax, jQuery, and PHP

In this tutorial, we are going to see how to submit Form Without Page Refresh Using Ajax, jQuery, and PHP. It’s common, that when we submit a web form or contact form, it takes a few seconds to submit it. AJAX has the option of submitting a form without refreshing the page. We will also be using AJAX with jQuery and PHP.
 

Step 1: Create an HTML form to submit the data

First, we will create a simple form to get user information. Create a page called “index.html” and paste the code below into it.

<html>
	<head>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
		<script type="text/javascript">
			// Put the Jquery code Here
		</script>
	</head>
	<body>	
	<form method="POST" onsubmit="return sendData();">
	   <input type="text" name="name" id="name">
	   <input type="text" name="age" id="age">
	   <input type="submit" name="submit_form" value="Submit">
	</form>

	<div id="res" ></div>

	</body>
</html>

 

 

Step 2: Submit the form with Ajax / jQuery

We will use the AJAX method to submit the form without refreshing the page.

function sendData()
{
	var name = document.getElementById("name").value;
	var age = document.getElementById("age").value;

	$.ajax({
		type: 'post',
		url: 'insert.php',
		data: {
		  name:name,
		  age:age
		},
		success: function (response) {
		  $('#res').html("Your data will be saved...");
		}
	});
		
	return false;
}

 

 

Step 3: Connect to the Database and Store Data

In this step, we get all the data that comes from the “index.html” page and store it in a database.

// insert.php file

<?php
  if( isset( $_POST['name'] ) )
  {

	  $name = $_POST['name'];
	  $age = $_POST['age'];

	  $con = mysqli_connect("localhost","root"," ","my_db");

	  $insert = " INSERT INTO user VALUES( '$name','$age' ) ";
	  mysqli_query($con, $insert); 

  }
?>

In this tutorial, we saw how to submit the form without refreshing the page. You can further customize this code according to your needs.
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “Submit Form Without Page Refresh Using Ajax, jQuery, and PHP

  • What if i want to get feedback from the submission, and catch that in my html page?

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *