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.
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
JQuery Form Example
and the source code for process.php
Your name is ".$_POST['name']." and your email is ".$_POST['email']."
";
?>
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.
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
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.
Wow, nice tutorial! It’s so easy and simple, thanks!
But how to validate a length of name?
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..
@syabac: thanks for sharing..
cool, thank for the tips
@syabac
thanks for the link
I needed this
submitHandler: function(form) {
… }
, huge thanx you saved a lot of time.
Thanx.
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!!
@mrdeeds: I don’t think there’s a way NOT to show the action url.
thanks,,,and what script to clear form field after that ???
Awesome code. Thanks for the post.
Looks like exactly what I’ve been looking for thanks
this is brilliant
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.
Is there anyway to submit the form without using a submit button, say when a text box is updated?
– how to clear fields
– alert messages don’t dissapear
– takes some time for submit message to appear
– not happy
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!!
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.
One more comment from my side.
I have tried equal, notequal and etc. All these rules breaks working of this script.
Anatoly.
Awsome, thx man
how to do it without refresing the page and without movin to another page?
thanks- that is great. it is very useful to me.
Pingback: 50 jQuery Form Plugins, Tutorials and Resources | webdesign14.com
submitHandler: function(form) {
// do other stuff for a valid form
How can i hide form after submission
Thank You very much for sharing.. This is what I’ve been looking for. It works! God bless.
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.
Great resource … Many thanks !
thanks
Very Good Example
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?
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/.
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!
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?
@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!
THANK YOU THANK YOU THANK YOU!!!!!
you miss nothing, the ACTION is left empty “”
its only display the message was send
Like wise – does not work locally
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’].”“;
?>
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 nn Email: $email nn 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’].”“;
?>
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?
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
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.
Good example 😉
thanks
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.”“;
}
?>
Pingback: Simple Ajax(PHP and jQuery: Submit a form without refreshing the page) « nawabpurwebs
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…
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!
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
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)
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
@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 "”;
?>
..?
i love it but I’m getting “No database selected” old the time..
Fantastic tutorial Worked like a dream!!
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?
how to auto detect the email
thanks a lot… please be the same.. don’t change…
and don’t stop helping others….
How do I get it to send the info to my email address?
nice..thanks.. how to do for two submit buttons and retrieving table from database..
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?
Pingback: jquery | Pearltrees
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.
Works great, thanks a lot. I hated having to refresh my php page…
edit: Oh, in case you wonder, I adapted it here, on a PHP script I wrote: http://www.flapane.com/calcolatore.php
This tutorial is great, however this doesnt actually work in IE browsers, only firefox/chrome/safari etc …
Thanks you
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..
Hello,
Can anyone tell me how to append the results if we submit the form twice?