PHP and jQuery: Submit a form without refreshing the page

Lately, I’ve been chancing on quite a number of posts at various places asking about how to perform a web action without the webpage reloading/refreshing? For example, dynamically updating a list on a page without a reload or submitting a form to PHP without leaving the webpage the form sits on.

I guess this is as good a time to start branching into some posts on PHP and Javascript, or more specifically, jQuery.


To be honest, I’ve never been partial to using Javascript (ie client-side programming) in my web applications, prefering instead to rely on server-side processing for all my programming needs. I guess this has to do with my frustrations of Javascript incompatibility between different browsers back in the day. However, with a javascript library (or framework) like jQuery, I’m starting to use more client-side actions to complement all the server-side PHP stuff. Here’s 6 reasons why you should use JavaScript Libraries & Frameworks.

You can download my example source code if it helps you understand how the whole thing works.

Download: download icon

And here’s a demo of what we’re trying to do.

The traditional way of doing form submissions
Back in the “old” days, in order to perform a form submission, you need to do something like this.

When you click the “Submit” button on form.php, the web server knows to send the name and email values using the POST method to the php script called process.php. The web server will load process.php page and the PHP script will start to read in the form values posted from form.php, maybe perform some validation to check that the information received is correct, then perhaps do something with the form values such as storing it in a database or sending it via email and output a “thank you” message.

What if something goes wrong, for example, the person submitting the form wrote in a badly-formed email address, the validation at process.php will throw a nicely worded error message and stop running the rest of the script. The person then would need to go back to the form to correct the email address and he would submit the form again.

This might have been an OK way of doing things 10 years ago, but in this era of Facebook and Twitter, that’s a pretty antiquated and tedious method.

The jQuery way of doing form submissions
Here’s the jQuery way, which is made possible by something called AJAX (which stands for Asynchronous JavaScript and XML). AJAX is bascially the technology that makes it possible to exchange data with a server, and update parts of a web page – without reloading the whole page. jQuery includes the necessary functions to implement AJAX into your web application.

The diagram looks quite similar to the “old” way of doing things, except that process.php is now represented by a ‘circle’. This is because process.php is now hidden for lack of a better word. In the traditional method, when you click the submit, your browser will load process.php and it will jump from form.php to process.php.

With the jQuery/AJAX way, process.php becomes a background process which the web server will call on, and when you click on the “Submit” button, form.php pushes the data to process.php, but your browser will remain showing form.php. Once the process.php has done what it needs to, it will return to form.php some output to be displayed.

Here’s the source code for form.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html>
<head>
	<title>JQuery Form Example</title> 
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
	<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/jquery.validate.min.js"></script>
	<script type="text/javascript">
	$(document).ready(function(){
		$("#myform").validate({
			debug: false,
			rules: {
				name: "required",
				email: {
					required: true,
					email: true
				}
			},
			messages: {
				name: "Please let us know who you are.",
				email: "A valid email will help us get in touch with you.",
			},
			submitHandler: function(form) {
				// do other stuff for a valid form
				$.post('process.php', $("#myform").serialize(), function(data) {
					$('#results').html(data);
				});
			}
		});
	});
	</script>
	<style>
	label.error { width: 250px; display: inline; color: red;}
	</style>
</head>
<body>
<form name="myform" id="myform" action="" method="POST">  
<!-- The Name form field -->
    <label for="name" id="name_label">Name</label>  
    <input type="text" name="name" id="name" size="30" value=""/>  
	<br>
<!-- The Email form field -->
    <label for="email" id="email_label">Email</label>  
    <input type="text" name="email" id="email" size="30" value=""/> 
	<br>
<!-- The Submit button -->
	<input type="submit" name="submit" value="Submit"> 
</form>
<!-- We will output the results from process.php here -->
<div id="results"><div>
</body>
</html>

and the source code for process.php

1
2
3
<?php
	print "Form submitted successfully: <br>Your name is <b>".$_POST['name']."</b> and your email is <b>".$_POST['email']."</b><br>";
?>

Here’s what’s happening
I included jQuery’s form validation because it provides a more real world example. Usually, most sites will perform processes like form validation at the client-side before the form is submitted. It’s just more intuitive and a much better user experience. In fact if you can offload as much workload as you can to the browser, it will greatly reduce the hit on your server.

So here’s a quick high-level walk through what’s happening on the jQuery part.

I call the validate method (make sure you have included the jquery validate plugin – see form.php Line 6) on my form #myform, and proceed to define what to validate. In this case, we’re checking that the name field is ‘required’, and we’re checking the email field is not only ‘required’, but must be an email format. I also define the custom error message I want to display if the validation fails.

Lastly, the submitHandler is what gets processed if the validation is successful. In this case, I’m doing an ajax post method, sending my form data to process.php, and get back any results as HTML data which will be displayed into #results.

Over at process.php, I’m simply printing out the data received to show you the information was sent and returned.

That’s basically it. If you want to know more, do check out the jQuery website to get more details on how to do AJAX and Validation.

Feel free to comment your thoughts or suggestions.

Share and Enjoy:
  • Digg
  • Sphinn
  • del.icio.us
  • Facebook
  • Mixx
  • Google Bookmarks
  • DZone
  • Propeller
  • Reddit
  • StumbleUpon
  • Technorati
  • Yahoo! Buzz
Posted on June 9, 2010 at 2:55 pm by Eldee · Permalink
In: PHP Tutorials · Tagged with: , ,

72 Responses

Subscribe to comments via RSS

  1. Written by Scott on January 3, 2012 at 1:11 pm
    Permalink

    Seems the system stripped part of my comments…

    It should read something like:

    To make the ‘name’ and ‘email’ dynamic you would use something like

    ThankYou.html?name= $name &email= $email

    Have to use PHP echo statement for $name and $email

    (system stripped my php comments)

  2. Written by hariom batra on January 30, 2012 at 2:32 pm
    Permalink

    process.php does not shows the image uplaoded (means process.php does not echo the $_FILES['fileField']['name'];
    and also does not upload the uploaded file to folder)

    $name = $_FILES['fileField']['name'];
    $uploaddir = ‘files/’;
    $uploaddir = $uploaddir . $name;
    $uploadfile = $name_updated;
    move_uploaded_file($_FILES['fileField']['tmp_name'], $uploaddir);

    this coding does not works. i added enctype=”multipart/form-data” in the form still not working

  3. Written by Stian on February 17, 2012 at 12:20 am
    Permalink

    @hariom batra: Maybe because you need to do something like this.

    <?php

    // The code you posted previously here
    $name = $_FILES['fileField']['name'];
    $uploaddir = ‘files/’;
    $uploaddir = $uploaddir . $name;
    $uploadfile = $name_updated;
    move_uploaded_file($_FILES['fileField'], $uploaddir);
    //To echo the image
    echo "”;
    ?>

    ..?

  4. Written by Soulast on February 17, 2012 at 3:26 am
    Permalink

    i love it but I’m getting “No database selected” old the time..

  5. Written by James on February 17, 2012 at 3:33 am
    Permalink

    Fantastic tutorial Worked like a dream!!

  6. Written by Soulast on February 17, 2012 at 4:08 am
    Permalink

    Never mind above i did sort my db connection but i have simple quesiton how od i add pre-loaidng img to it while placing data in to db?

  7. Written by nicky on February 17, 2012 at 11:57 am
    Permalink

    how to auto detect the email

  8. Written by reme101 on February 19, 2012 at 11:06 pm
    Permalink

    thanks a lot… please be the same.. don’t change…
    and don’t stop helping others….

  9. Written by Aaron on February 27, 2012 at 9:58 am
    Permalink

    How do I get it to send the info to my email address?

  10. Written by Rosy on February 29, 2012 at 1:49 pm
    Permalink

    nice..thanks.. how to do for two submit buttons and retrieving table from database..

  11. Written by Austin on March 1, 2012 at 10:54 pm
    Permalink

    How can this script post arrays to a php script. Currently I use a select multiple form element where the users selection(s) must be turned into an array before being posted to a php script. I do this by adding “[]” to the form element name ie. name=”list[]“. When the submit data is sent to my php script none of the array values are sent over, it completely skips over anything from the select multiple form element. Is there a workaround for this problem?

  12. Written by jquery | Pearltrees on April 11, 2012 at 7:23 pm
    Permalink

    [...] I guess this is as good a time to start branching into some posts on PHP and Javascript, or more specifically, jQuery. To be honest, I’ve never been partial to using Javascript (ie client-side programming) in my web applications, prefering instead to rely on server-side processing for all my programming needs. PHP and jQuery: Submit a form without refreshing the page | Ask About PHP [...]

  13. Written by Eric on June 6, 2012 at 1:41 am
    Permalink

    How would I use this to have the form set a SESSION variable based on a dropdown box selection? I am not sure where to put the SESSION code in the script part. I do understand where to put it in the process.php.

  14. Written by flapane on June 8, 2012 at 4:51 am
    Permalink

    Works great, thanks a lot. I hated having to refresh my php page…

  15. Written by flapane on June 8, 2012 at 4:58 am
    Permalink

    edit: Oh, in case you wonder, I adapted it here, on a PHP script I wrote: http://www.flapane.com/calcolatore.php :)

  16. Written by Tribune on June 19, 2012 at 10:50 am
    Permalink

    This tutorial is great, however this doesnt actually work in IE browsers, only firefox/chrome/safari etc …

    :(

  17. Written by shahzad on August 2, 2012 at 2:02 pm
    Permalink

    Thanks you

  18. Written by Serkan on August 28, 2012 at 8:01 pm
    Permalink

    can anybody help me to validate multiple forms with the technique shown below please..
    >I have a page which contains more than one form and will contain more and more..Andd I don’t want to refresh whole page if any of them is posted.
    This example is very useful while working with only one form..

    But when it comes to play with more than one form I am not able to handle them. Especially while formN is result of formN-1.

    Let me give try to show you my problem with some simple code..

    <<>>

    $(document).ready(function(){

    $(“#form1″).validate({
    debug: true,
    rules: {
    name: “required”,
    },
    messages: {
    name: “Please let us know your firstname.”,
    },
    submitHandler: function(form) {
    $.post(‘form2.php’, $(“#form1″).serialize(), function(data) {
    $(‘#myDiv2′).empty().replaceWith(data);// i can use html() or …empty ().append()..all is ok for me if anybody can succeed with it :)
    });
    $(“#myDiv1″).css(‘visibility’,'hidden’);//hide() is ok for me also.This is just one of my tests..
    $(“#myDiv2″).css(‘visibility’,'visible’);// show() can be ok …

    }
    });

    $(“#form2″).validate({
    debug: true,
    rules: {
    surname: “required”,
    },
    messages: {
    surname: “Please let us know your surname.”,
    },
    submitHandler: function(form) {
    $.post(‘form3.php’, $(“#form2″).serialize(), function(data) {
    $(‘#myDiv3′).empty().replaceWith(data);
    });
    $(“#myDiv2″).css(‘visibility’,'hidden’);
    $(“#myDiv3″).css(‘visibility’,'visible’);
    }
    });

    $(“#form3″).validate({
    debug: true,
    rules: {
    pet: “required”,
    },
    messages: {
    pet: “Please let us know your pet name.”,
    },
    submitHandler: function(form) {
    $.post(‘form4.php’, $(“#form3″).serialize(), function(data) {
    $(‘#myDiv4′).empty().replaceWith(data);
    });
    $(“#myDiv3″).css(‘visibility’,'hidden’);
    $(“#myDiv4″).css(‘visibility’,'visible’);
    }
    });

    });

    label.error { width: 250px; display: inline; color: red;}

    <<>>

    Your FirstName*:

    Email Address*:

    UserName*:

    Password*:

    <<>>

    Your surname*:

    Job*:

    Town*:

    Eye Color*:

    <<>>

    Your age*:

    Pet Name*:

    Mother Name*:

    <<>>

    Your sex*:

    As you can see one form is submitted and its result is another form..another ..and another.

    I have played a lot with these example but could not find a solution in any way..

  19. Written by Serkan on August 28, 2012 at 8:02 pm
    Permalink
    can anybody help me to validate multiple forms with the technique shown below please..
    >I have a page which contains more than one form and will contain more and more..Andd I don't want to refresh whole page if any of them is posted.
    This example is very useful while  working with only one form..
    
    But when it comes to play with more than one form I am not able to handle them. Especially while formN is result of formN-1.
    
    Let me give try to show you my problem with some simple code..
    
    <<>>
    
    $(document).ready(function(){
    
    	$("#form1").validate({
    			debug: true,
    			rules: {
    				name: "required",
    			},
    			messages: {
    				name: "Please let us know your firstname.",
    			},
    			submitHandler: function(form) {
    				$.post('form2.php', $("#form1").serialize(), function(data) {
    					$('#myDiv2').empty().replaceWith(data);// i can use html() or ...empty ().append()..all is ok for me if anybody can succeed with it :)
    				});
    				$("#myDiv1").css('visibility','hidden');//hide() is ok for me also.This is just one of my tests..
    				$("#myDiv2").css('visibility','visible');// show() can be ok ...
    
    			}
    		});
    
    		$("#form2").validate({
    			debug: true,
    			rules: {
    				surname: "required",
    			},
    			messages: {
    				surname: "Please let us know your surname.",
    			},
    			submitHandler: function(form) {
    				$.post('form3.php', $("#form2").serialize(), function(data) {
    					$('#myDiv3').empty().replaceWith(data);
    				});
    				$("#myDiv2").css('visibility','hidden');
    				$("#myDiv3").css('visibility','visible');
    			}
    		});
    
    		$("#form3").validate({
    			debug: true,
    			rules: {
    				pet: "required",
    			},
    			messages: {
    				pet: "Please let us know your pet name.",
    			},
    			submitHandler: function(form) {
    				$.post('form4.php', $("#form3").serialize(), function(data) {
    					$('#myDiv4').empty().replaceWith(data);
    				});
    				$("#myDiv3").css('visibility','hidden');
    				$("#myDiv4").css('visibility','visible');
    			}
    		});
    
    });
    
    	label.error { width: 250px; display: inline; color: red;}
    
    <<>>
    
    	Your FirstName*: 
    
    	Email Address*:
    
    	UserName*:
    
    	Password*:
    
    <<>>
    
    	Your surname*: 
    
    	Job*:
    
    	Town*:
    
    	Eye Color*:
    
    <<>>
    
    	Your age*: 
    
    	Pet Name*:
    
    	Mother Name*:
    
    <<>>
    
    	Your sex*: 
    
    As you can see one form is submitted and its result is another form..another ..and another.
    
    I have played a lot with these example but could not find a solution in any way..
    
  20. Written by Arindam Barman on November 3, 2012 at 12:57 pm
    Permalink

    Hello,

    Can anyone tell me how to append the results if we submit the form twice?

  21. Written by Vishal on May 30, 2013 at 6:02 pm
    Permalink

    Thanks for the simple script.

  22. Written by vinuta on June 8, 2013 at 12:44 pm
    Permalink

    hello, I am trying to validate registration form using same code above. But finding a error “Uncaught Type Error: Cannot call method call of undefined” validate.min.js:15
    can any one help me..
    thanks

Subscribe to comments via RSS

Leave a Reply