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: , ,

52 Responses

Subscribe to comments via RSS

  1. Written by Tomas Dermisek on June 10, 2010 at 2:44 pm
    Permalink

    Hi,

    I like this example, but one should not forget that user can tamper post data and thus send different values than validated through js. Therefore the server side validation is a must and client side validation should be done only on top of it as some usability (user experience) improvement.

    You can easy try this in Firefox using the Tamper Data add-on.

    Regards,

    Tomas

  2. Written by webmaster on June 10, 2010 at 11:12 pm
    Permalink

    hi Tomas
    You are right, that is a very valid point! My post was focused on how to use jQuery, but we should not neglect the security of our scripts in the backend too.

  3. Written by arnis on June 11, 2010 at 7:56 pm
    Permalink

    Wow, nice tutorial! It’s so easy and simple, thanks!
    But how to validate a length of name?

  4. Written by syabac on July 10, 2010 at 12:33 pm
    Permalink

    Hi arnis,
    you can read more documentation at
    http://docs.jquery.com/Plugins/Validation/Methods/minlength#length

    i’ve try it on my application, and it works..

  5. Written by san on July 10, 2010 at 1:04 pm
    Permalink

    @syabac: thanks for sharing..

  6. Written by yohan on July 11, 2010 at 10:40 pm
    Permalink

    cool, thank for the tips :)

  7. Written by ranggaw0636 on July 15, 2010 at 11:56 am
    Permalink

    @syabac
    thanks for the link

  8. Written by freak on July 23, 2010 at 8:32 pm
    Permalink

    I needed this
    submitHandler: function(form) {
    … }

    , huge thanx you saved a lot of time.
    Thanx.

  9. Written by mrdeeds on July 29, 2010 at 10:52 pm
    Permalink

    Thank you!!!
    So…
    Is there anyway to submit a form without action url and don’t show the actiion file:
    submitHandler: function(form) {
    // do other stuff for a valid form
    $.post(‘process.php’, $(“#myform”).serialize(), function(data) {
    $(‘#results’).html(data);
    });
    }
    I don’t want to show the process.php file…
    Can you help me?!
    Thanks again!!

  10. Written by webmaster on July 30, 2010 at 10:23 am
    Permalink

    @mrdeeds: I don’t think there’s a way NOT to show the action url.

  11. Written by zaki on October 4, 2010 at 2:07 pm
    Permalink

    thanks,,,and what script to clear form field after that ???

  12. Written by MrBroom on October 5, 2010 at 10:52 pm
    Permalink

    Awesome code. Thanks for the post.

  13. Written by Ryan on October 9, 2010 at 5:29 am
    Permalink

    Looks like exactly what I’ve been looking for thanks

  14. Written by tosan on October 11, 2010 at 11:23 pm
    Permalink

    this is brilliant

  15. Written by Pwkicks on October 12, 2010 at 1:43 am
    Permalink

    thanks- that is great.

    Question: If I want to write the data to a database does that happen in the submitHandler or in the process.php. Do you have an sample code for that.

  16. Written by Ryan on October 13, 2010 at 2:03 am
    Permalink

    Is there anyway to submit the form without using a submit button, say when a text box is updated?

  17. Written by johnny on November 1, 2010 at 5:16 pm
    Permalink

    - how to clear fields
    - alert messages don’t dissapear
    - takes some time for submit message to appear
    - not happy

  18. Written by Yahfree on November 22, 2010 at 1:28 am
    Permalink

    Hey! when I try this and do some mysql stuff in process.php, the echo statements don’t work anymore!

    But when I remove(comment out) the database stuff, the echo statements work again. Why is this? It’s super frustrating!!

  19. Written by Anatoly on November 28, 2010 at 6:41 am
    Permalink

    This is very usefull topic and example.
    Thanks for publishing.
    I am trying to implement it and have an issue with “notquel” rule.
    Then I add new rule:
    name: {
    required: true,
    notEquals: ‘q’
    },
    After entering any string an application doesn’t notice about an error like it happens with empty string..

    Thanks in advice,
    Anatoly.

  20. Written by Anatoly on November 29, 2010 at 4:52 am
    Permalink

    One more comment from my side.
    I have tried equal, notequal and etc. All these rules breaks working of this script.

    Anatoly.

  21. Written by Fresh on December 5, 2010 at 3:37 am
    Permalink

    Awsome, thx man

  22. Written by saurabh on December 10, 2010 at 1:05 pm
    Permalink

    how to do it without refresing the page and without movin to another page?

  23. Written by baby hats on January 17, 2011 at 3:38 pm
    Permalink

    thanks- that is great. it is very useful to me.

  24. [...] 3. PHP and jQuery: Submit a form without refreshing the page [...]

  25. Written by Catalin on February 28, 2011 at 9:50 pm
    Permalink

    submitHandler: function(form) {
    // do other stuff for a valid form
    How can i hide form after submission

  26. Written by Glenn on March 23, 2011 at 7:32 pm
    Permalink

    Thank You very much for sharing.. This is what I’ve been looking for. It works! God bless.

  27. Written by James on April 28, 2011 at 2:15 pm
    Permalink

    Great guide. One question, can you give tips on how to disable or hide the submit button after a successful submission? I decide if the submission was successful based on the html process.php returns.

  28. Written by Baz on May 26, 2011 at 4:41 pm
    Permalink

    Great resource … Many thanks !

  29. Written by abc on June 8, 2011 at 1:40 am
    Permalink

    thanks

  30. Written by Jorge on June 14, 2011 at 10:05 pm
    Permalink

    Very Good Example

  31. Written by hale on June 16, 2011 at 12:02 am
    Permalink

    Hello,
    It doesnt work on Safari, when I submit form, the whole page refresh (as press F5).
    I also change name of submit button, not work
    Do you know how to resolve this?

  32. Written by Darrell on June 23, 2011 at 3:30 pm
    Permalink

    In answer to two of the questions:

    @mrdeeds: Is there any way to submit a form without action url and don’t show the actiion file:

    @Ryan: Is there any way to submit the form without using a submit button, say when a text box is updated?

    @mrdeeds – You have to have a known url to go to.
    It can be the base url with post values that determine which action to perform or as in the example a specific action url. You can name the processing url anything you want.

    @Ryan – You can “hook” any event on any element you want, so, creating a function that “hooks” a textbox’s “onblur()” event to trigger the form submission. By the way, the onblur() event is one MS got correct and FF and others should have followed suit – IMHO.

    See: http://api.jquery.com/blur as it handles many of the x-browser inconsistencies; although due to “bubbling” that might be caused by jQuery’s mapping to the focusout() method, you might still need to ensure the correct element triggered the function and not a parent. Also see: http://api.jquery.com/focusout/.

  33. Written by Darrell on June 23, 2011 at 3:34 pm
    Permalink

    By the way, this is one of the simplest and straight forward explanations I’ve ever seen of jQuery’s form submission and validation functionality.

    Great job!

  34. Written by connie on July 11, 2011 at 5:03 am
    Permalink

    I downloaded your zip file and ran it locally, but it did not work. The form appears but nothing happens when I click submit. What am I missing?

  35. Written by Praveen on August 7, 2011 at 11:13 am
    Permalink

    @Catalin
    That is a very simple job. All you need to do is, use the jQuery hide function for that purpose.

    $(“form”).hide();

    Hope, this will help!

  36. Written by charlie on August 7, 2011 at 1:51 pm
    Permalink

    THANK YOU THANK YOU THANK YOU!!!!!

  37. Written by dim on August 16, 2011 at 11:41 am
    Permalink

    you miss nothing, the ACTION is left empty “”
    its only display the message was send

  38. Written by Mav on August 17, 2011 at 2:21 pm
    Permalink

    Like wise – does not work locally

  39. Written by dan on August 27, 2011 at 10:43 pm
    Permalink

    hello, in process.php i am trying to send email on a simple
    submit bid form with just name and email fields.
    located here http://ecorporate.biz

    in process.php my code does not send mail. here is my code.
    any help is greatly appreciated as this is useless if i cannot get it to send me the info in an email. i do not want to store on server.
    <?php
    /*
    $name = $_POST['name'];
    $email = $_POST['email'];
    $to = “1@highlinecorporation.com”;
    $subject =” Bid Request from eCorporate.biz and mail “.$email;
    $message =” You received a Bid Request from “.$email;
    $message .=” Bid Requestee Name : “.$name;
    if(email($to, $subject,$message)){
    echo “mail successfully sent”;
    }
    */

    print "Form submitted successfully: Your name is Recorded as “.$_POST['name'].” and your Sent email Address Was “.$_POST['email'].”“;

    ?>

  40. Written by dan on August 27, 2011 at 11:58 pm
    Permalink

    Never Mind. I Just got it with this as process.php code.

    <?php
    $to = "1@highlinecorporation.com";
    $subject = "Contact Form Submission";
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["comment"];
    $body = "From: $name \n\n Email: $email \n\n Message: $message";
    $sent = mail($to, $subject, $body) ;

    if($sent)
    {
    print "The Message was sent successfully“;
    }
    else
    {
    print “There was a problem with sending the message“;
    }

    print “Form submitted successfully: Your name is Recorded as “.$_POST['name'].” and your Sent email Address Was “.$_POST['email'].”“;

    ?>

  41. Written by Jim on August 31, 2011 at 10:54 pm
    Permalink

    Perhaps a really stupid question, but where’s the part in the php that sends the actual email and where’s the email listed to which the message is sent?

  42. Written by Nikola Stojanović on September 12, 2011 at 2:58 am
    Permalink

    Hello,

    is it possible to use this with forms which include file inputs ?
    I tried and it seems it does not pass files (images, in my case) to my process.php.

    Regards,
    Nikola

  43. Written by Ray D on September 19, 2011 at 1:56 pm
    Permalink

    Hi
    Great stuff here! Thanks!

    I ‘m trying to take the $name from the contact form
    and not only email it back to me ( which i’ve done already) but have appear as text in another ThankYou.html file that will be called by the sendmail.php file. Thus i can’t ONLY use . So basicly i’m trying to get all the Input field from the Form.php page to the sendmail.php and if all is validated and correct , then send an email with the data AND also take the $name from the form and display on the thankyou html page .

    Again, all is working except the last step displaying the name on the ThankYou.html page.

  44. Written by ekkahi on September 26, 2011 at 7:19 pm
    Permalink

    Good example ;)

  45. Written by maulik on September 28, 2011 at 8:49 pm
    Permalink

    thanks

  46. Written by waseem on October 25, 2011 at 7:55 pm
    Permalink

    i want to upload teh file with this form kindly help me it is not uploading file

    my code is

    JQuery Form Example

    $(document).ready(function(){
    $(“#myform”).validate({
    debug: false,
    rules: {
    name: “required”,
    vdo: “required”,
    },
    messages: {
    name: “Please give the title of image”,
    vdo: “Please select the image”,
    },
    submitHandler: function(form) {
    // do other stuff for a valid form
    $.post(‘form.php’, $(“#myform”).serialize(), function(data) {
    $(‘#results’).html(data);
    });
    }
    });
    });

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


    Title


    Image

    <?php
    /*
    Here's where you want PHP to process the form data and do something with it, for example inserting the data into a database or sending the information to an email address and so on
    */

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

    $banner_image= $_FILES['vdo']; // file name in the form

    $banner_file= $_FILES['vdo']['name'];

    $img_name="";

    $info = pathinfo($banner_file);

    $ext2 = strtolower($info['extension']);

    $b = uniqid(rand (),true);
    $img_nameb ="image".$b.".". $ext2;

    $nadd3="upload/".$img_nameb; // banner_images is actually the folder name where the image is placed

    move_uploaded_file($_FILES['vdo']['tmp_name'], $nadd3);

    print "Form submitted successfully: Your name is “.$_POST['name'].” image path “.$nadd3.”“;

    }
    ?>

  47. [...] 1: http://www.askaboutphp.com/213/php-and-jquery-submit-a-form-without-refreshing-the-page.html Share this:TwitterFacebookLike this:LikeBe the first to like this post. [...]

  48. Written by Jason on November 13, 2011 at 5:17 am
    Permalink

    Great stuff, but… i get all kinds of stuff in the output of the post command like this

    “POST / HTTP/1.1
    Host: xxxx.xxxxx.com:8080
    Connection: keep-alive
    Content-Length: 20
    Origin: http://xxx.xxxxx.com
    User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.120 Safari/535.2
    Content-Type: application/x-www-form-urlencoded
    Accept: */*
    Referer: http://xxxxx.xxxxx.com/1test.html
    Accept-Encoding: gzip,deflate,sdch
    Accept-Language: en-US,en;q=0.8
    Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

    name=1&submit=Submit”

    My question is how can i submit ONLY the actual characters that are input. in the above example all i would like to receive would be “1″ (without the quotes as that is what i put in the box). Is this possible? i have a terminal app on the other end that is expecting only one ascii character…

  49. Written by adrian on November 25, 2011 at 6:53 pm
    Permalink

    Can you please give me the exact synatx to put in “Process.php” so that this can be sent to an email ?
    I am trying :

    But not workig!

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

    Questions:
    @Jim – Perhaps a really stupid question, but where’s the part in the php that sends the actual email and where’s the email listed to which the message is sent?

    Answer:
    mail($to, $subject, $body) is what actually sends the mail message.
    $_POST["email"]; is what gets the email address from the submitted form.

    @Ray D – I ‘m trying to take the $name from the contact form
    and not only email it back to me ( which i’ve done already) but have appear as text in another ThankYou.html file that will be called by the sendmail.php file.

    Answer: With PHP you cannot pass variables between pages directly. Any variables used and information stored in them will be cleared and lost when you leave the current page. There are 2 ways you could pass the information:
    (1) You can store the information in the session and retrieve it in the next page using Something like:

    $_SESSION['name'] = $name;

    which will store the variable contents in the session and then you can retrieve it from any page using

    $variable = $_SESSION['name'];

    Of course you have to have a session started before you can use this method.

    or

    (2) you can pass the information as part of the HTML URL similar to:

    ThankYou.html?name=name&email=email

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

    ThankYou.html?name=&email=

    Change the $name and $email to whatever variables you use for them in your script. This will print the $name and $email variable contents directly into the HTML URL

    Then you get the information on the ThankYou.html page (right at the top) by

    $name = $_GET['name'];
    $email = $_GET['email'];

    I personally prefer method 1 as method 2 is open to security issues as anyone could change the name and email values by simply typing them into the URL. Plus Method 1 allows you to store and use that information anywhere in the website. Once you are done with the information in the session you can clear it by:

    unset ($_SESSION['name']);
    Which clears that session variable but leaves your session in tact

Subscribe to comments via RSS

Leave a Reply