Submit a form without page refresh PHP & jQuery

Submit a form without page refresh PHP & jQuery

In this tutorial we have a simple form with name, email & phone number. The form submit all fields to a PHP script without page refresh, using native jQuery method (native meaning, you don’t need to download any extra plugins to make it work.

First of all you need to make a HTML form.

HTML Code

<form action="submit.php"  method="post">
 Name: <input name="name" id="name" type="text" /><br />
 Email: <input name="email" id="email" type="text" /><br />
 Phone Number: <input name="phone" id="phone" type="text" /><br />
 <input type="button" id="searchForm" onclick="SubmitForm();" value="Send" />
 </form>

 JavaScript Code

Simple JavaScript Code

<script src="http://code.jquery.com/jquery-latest.js"></script>
 
<script>
function SubmitForm() {
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
$.post("submit.php", { name: name, email: email, phone: phone },
   function(data) {
     alert("Data Loaded: " + data);
   });
}
</script>

JavaScript Library Include

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

 PHP Code

Simple PHP Action File

<?php

if( $_SERVER[ 'REQUEST_METHOD' ] == 'POST' ) {
	echo $_POST[ 'name' ] . "<br />";
	echo $_POST[ 'email' ] . "<br />";
	echo $_POST[ 'phone' ] . "<br />";
	echo "All Data Submitted Sucessfully!";
	die();
}

?>

 

Author Surjit Sidhu

Surjit SidhuSurjit is a student of IT, a freelance web designer/developer and a tech writer. He deals with both front-end and back-end stuff. Whenever he is not in front of an Internet-enabled device he is probably reading a book or traveling.