Thursday, June 10, 2010

Submit a form without refreshing the page with Jquery and PHP

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 loadprocess.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 forAsynchronous 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

<!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



<?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.


People who read this post also read :



If you liked my post then,

Subscribe to this site via Email:

Click here to Subscribe to FREE email updates from "itrickz", so that you do not miss out anything that can be valuable to you and your blog!!

DropJack!
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

12 comments: on "Submit a form without refreshing the page with Jquery and PHP"

Las Vegas Web Design said...

Where could I try this? Any demo? Thank you very much for this.
Las Vegas Web Design

Anonymous said...

I think this is among the most vital info for me. And i am glad
reading your article. But want to remark on some general things, The web site style is wonderful,
the articles is really nice : D. Good job, cheers

Also visit my web-site ... plus de followers

Anonymous said...

Hey there just wanted to give you a brief heads up and let you know a few of
the pictures aren't loading properly. I'm not sure why but I think its a linking issue.
I've tried it in two different browsers and both show the same results.

Feel free to surf to my web blog plus de vues youtube

Anonymous said...

I'm extremely impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you modify it yourself? Anyway keep up the nice quality writing, it's
rare to see a great blog like this one today.

Feel free to visit my website; email templates for gmail

Anonymous said...

wonderful points altogether, you simply won a logo new reader.
What would you suggest about your post that you made
a few days ago? Any certain?

Here is my blog post; free email templates

Anonymous said...

This is my first time go to see at here and i am actually happy
to read everthing at alone place.

Feel free to surf to my web page :: meliorism

Anonymous said...

Greetings! Very helpful advice in this particular article!
It's the little changes that will make the greatest changes. Thanks a lot for sharing!

Also visit my web-site ... Mouse Click The Next Site

Anonymous said...

Very good blog! Do you have any helpful hints for aspiring
writers? I'm hoping to start my own website soon but I'm a
little lost on everything. Would you recommend starting with a free platform
like Wordpress or go for a paid option? There are so many choices out there that I'm completely overwhelmed .. Any tips? Thank you!

Here is my web-site; tenderfoot

Anonymous said...

Great article! This is the kind of info that should be shared
around the web. Shame on Google for now not positioning this put up higher!

Come on over and seek advice from my site . Thanks =)

Feel free to visit my blog post - Email Marketing System

Anonymous said...

Hi, just wanted to tell you, I liked this post.
It was practical. Keep on posting!

my page; Free Christmas Email Templates

Anonymous said...

Nowadays, I've truly season abandoned to compete my best Bachelors Stage in corporate Government.


So there are lots of cities somewhere can present you with
one of the automatic 7steps loans and therefore you
need to is simply be aware of specifically where most of these
sets tend to be and ways in which it's possible to receive the
thing you, yourself are immediately after.
Clearly there was clearly very little costumes washer dryer anyplace in the pricing for the
a single from your full-page post. Money, all the paths intended for borrowing from
the bank funds in an effective solution, which is usually using credit institutes together with other finance
companies, have grown to be impossible from the rigid authorities laws regarding offering
credit and so loaning regarding income. auto title loans in md So there are lots of cities somewhere can present you with one of the automatic 7steps loans and therefore
you need to is simply be aware of specifically where most of
these sets tend to be and ways in which it's possible
to receive the thing you, yourself are immediately after.

Clearly there was clearly very little costumes washer dryer anyplace in the pricing for
the a single from your full-page post. Money, all the paths intended for borrowing from the bank
funds in an effective solution, which is usually using credit institutes together
with other finance companies, have grown to be impossible
from the rigid authorities laws regarding offering credit and so
loaning regarding income.

Anonymous said...

TҺese times can be threе or six months, or even еight months to a year.
For example, if you give employees a travel advance, they must submit an expense
rеport and return the portion of the advance theƴ Ԁid not
use, oг you must pay the employees forr their excess expenses over the amount of thee advance, within a reasonable period.
You еveen hae the precise to suboet your timeshare when you're authorized to make use օf it.


Look into my web blog :: travel advisor, ,

Post a Comment