A very simple tutorial submitting HTML form values without refreshing page using jQuery and Ajax. Just implement this and enrich your web applications.
Download Script Live Demo
Java Script Code:
jQuery and Ajax script take a look at dataString
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var username = $("#username").val();
var password = $("#password").val();
var gender = $("#gender").val();
var dataString = 'name='+ name + '&username=' + username + '&password=' + password + '&gender=' + gender;
if(name=='' || username=='' || password=='' || gender=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
libs/jquery/1.3.0/jquery.min.js">
</script>
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var name = $("#name").val();
var username = $("#username").val();
var password = $("#password").val();
var gender = $("#gender").val();
var dataString = 'name='+ name + '&username=' + username + '&password=' + password + '&gender=' + gender;
if(name=='' || username=='' || password=='' || gender=='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
HTML Code
<form method="post" name="form">
<ul><li>
<input id="name" name="name" type="text" />
</li><li>
<input id="username" name="username" type="text" />
</li><li>
<input id="password" name="password" type="password" />
</li><li>
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</li></ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div></form>
<ul><li>
<input id="name" name="name" type="text" />
</li><li>
<input id="username" name="username" type="text" />
</li><li>
<input id="password" name="password" type="password" />
</li><li>
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
</li></ul>
<div >
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div></form>
join.php
<?php
if($_POST)
{
$name=$_POST['name'];
$username=$_POST['username'];
$password=$_POST['password'];
$gender=$_POST['gender'];
mysql_query("SQL insert statement.......");
}else { }
?>
Related Posts :
Perfect Javascript Form Validation using Regular Expressions.
Twitter Like More Button with jQuery and Ajax.
Exactly Twitter like Follow and Remove buttons with jQuery and Ajax
Upload and Resize an Image with PHP
Easier: var data=$('#theform').serialize();
ReplyDeleteHello I just tried it on my website but it came out with an error saying : Method Not Allowed
ReplyDeleteThe requested method POST is not allowed for the following URL : /file/myform.html
I put in the file of course the "join.php" Did I forget something else ?
Wrong:
ReplyDeleteurl: "/file/join.php"
Write:
url: "http://domain.com/file/join.php"
There are some excellent jQuery plugins for this.
ReplyDeleteNo need to reinvent the wheel.
hi. why dont use Jquery form Plugin?
ReplyDeleteWhy not build your own?
ReplyDelete@Srinivas : me again (2d anonymous!) Thanks for the tip (url: "http://domain.com/file/join.php") but I actually had it done this way too with the complete url..
ReplyDeleteWhat about the SQL query ?
isn't this better.
ReplyDeleteMootools:
$('myForm').addEvent('submit', function(e) {
e.stop();
this.set('send', {onComplete: function(response){}});
//send the normal form..
this.send();
});
@nocturnal, You can do that with jQuery also. Infact, with jQuery 1.3, you can now do live events. So you can watch for a form submit whether the form is on the page yet or not. Only problem is that it isn't supported in early browsers (think IE5.5).
ReplyDeleteHeey great tutorial! :D
ReplyDeleteOne thing, can you maybe add a emailvalidation for this script?:)
Keep up the good work!!
vgf
ReplyDeletehow can i add the loading image while processing?
ReplyDeletewhat's wrong with code? , when i press send button it just reload the page, it didn't perform any function or query?
ReplyDeleteplease replay to me
Did u link with jQuery plug-in
ReplyDeleteHello, I did link with the plug-in, and I am having the same result as Ahmed. I can get the success indicator to show on the screen, but the database query is never run. I am sure I am using the right path to my join.php (http://test/intranet/join.php), but I don't understand why it doesn't execute the query.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteI've figured out a large part of my trouble, which was my data string (no ampersand in front of one field name, which caused the WHERE clause to return false).
ReplyDeleteI can now execute the query IF I have only one form on the page, but it doesn't seem to work with multiple forms. I have my forms named the same as the primary index of the query table, and I am using a hidden field to carry that value to the ".submit" function.
Hi Tim,
ReplyDeleteSend your files to my email id: [email protected]
I had actually sent them to you through Gmail on June 2nd. The e-mail is signed Tim Wallace. Thank you for taking the time to look.
ReplyDeleteHello Tim,
ReplyDeleteI did not get any mail your side- send to [email protected] or [email protected]
Srinivas Tamada
I was wandering of doing something like this for comment system but when it adds the comment it also show sit without page refresh how can this be done.
ReplyDeleteHi Sam Bennett
ReplyDeleteTake a look at this link http://9lessons.blogspot.com/2009/06/comment-system-with-jquery-ajax-and-php.html
useful
ReplyDeleteIm using your code with CMS system
ReplyDeletethe validation work good and the success message.
the url not working even with url: "http://domain.com/file/join.php" as you said??
can you help me ?
Twice in less than a week your blog has come up on my google searches looking for javascript elated solutions. Keep up the good work!!! You rock!!!!!
ReplyDeleteFan in Nigeria!!!!
Thank You Nigeria
ReplyDeletebfd
ReplyDeleteNope, wont work with the current jquery
ReplyDeleteIs it safe to send the password via AJAX to a PHP script? For instance if you check Firebug you can see the password string being send to the server.
ReplyDeleteHello Sir.... This was what i was exactly trying to achieve. I had a form inside jqueryUI tabs but i was facing problems while posting the form... Your method is really much simple and i am using it on my form.. Thanks for the great script...
ReplyDeleteOne main problem I am having with this is updating checkboxes. It is no problem submitting when you FIRST check a box. But what if you want to uncheck a box. Every time I un check a box it does not carry a null value over to the database. Any ideas would be appreciated.
ReplyDeleteIgnore the last message. I have resolved that issue. Now the issue is submitting on one form when I have multiple forms that contain the same inputs. Whenever trying to update one of the lower forms on the page, it always defaults to the values of the first form on the page. Is there any way to give the script a form id or name to get it's values from?
ReplyDeleteThanks Again,
Derek
Hi nice tutorial thanks, I was wondering how to add the recipient email address. any help would be appreciated
ReplyDeleteas others have said there is plugins that do all this for you
ReplyDeletehttp://jquery.malsup.com/form/#getting-started
Hi,
ReplyDeleteI just tried that and everything works fine until I send the data to the php script.
The $_POST['someVariable'] is always empty.
I tried sending the data with the serialize method and I alerted out the string to make sure that it wasn't empty which it wasn't and then I wrote out the string like you did in this example and the value is always empty in the php script. I made sure that I don't have spelling mistakes in the names of the variables. What could it be? Thanks.
Hi,
ReplyDeleteyour code is good. But
I just tried array of form data, so how can i change this code.
please help me
Hi srinivas....:)
ReplyDeleteGreat tutorial again..
I have a question:
After submiting i want clear the textfield.
how to do that...???
plz Help
Thanx
To clear textfields after submitting:
ReplyDelete$('#name').val('');
$('#username').val('');
$('#password').val('');
add the above lines after
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
in Java Script code
Hi srinivas....:)
ReplyDeleteGreat tutorial again..
Hello I am curious to know what the solution to using multiple forms on one page, each with their own submit and unique IDs.
ReplyDeleteI am making an image approval script, it reads all images in a directory and creates forms for each. I am unable to use onSubmit="action()" using ajax/jquery with multiple forms on the page.
Can you please give me a hand with this? My email is prodigymix at gmail dot com
Thanks!
Hi.
ReplyDeleteI´m trying to make a facebook connect submit form where ppl can update their status from my homepage.
When I change this:
url: "join.php",
to
url: "https://graph.facebook.com/<%=fbUid%>/feed",
(something I must do)
the form stops working. the whole page refreshes when I submit and nothing gets posted and theres no message in the DIV...
if i try to post to a local file the form and script works as it should.
ex.
url: "test.asp",
or
url: "http://www.mydomain.com/test.asp",
is this script not working with external url´s?
Thank you so much for this script!
ReplyDeleteI just need to know what code to write in the join.php so I can receive what was filled in the form in my e-mail.
The simple the better, please.
Thank you again!
thanx boss
ReplyDeleteWhat if I wanted to submit the form to send an email instead.
ReplyDeleteThe form in question only has one field and here is the php I used:
Thanks
hi,
ReplyDeleteHow could i do the same with a file? Is it possible to Submit a Form with a file without Refreshing page?
Thanks
Real Great Tutorial. Thanks Guys
ReplyDeleteDeji
hi
ReplyDeletegood
What if your sql insert failed and you want to display the error which you have received from the database server.
ReplyDeletePlease help...
i cant get work ratio.
ReplyDeleteis shows always a first parametr. Anyone else the same ? thanks
Hi if I were to have two forms with the same class names for each input in each form how would I make it so that only the data from the form I submitted gets sent to the php script and not just the contents of the first form? I know it has something to do with $(this) but I can't figure it out.
ReplyDeleteThe forms are outputted through php and there's no definite amount of them. I guess it's something similar to the way facebook commenting works on everyones main feed.
Hopefully someone can help me!
Hi, good tutorial. It works fine for me except that whenever the form error submission (in case of invalid data) is followed by a valid submission, the SQL is processed twice generating duplicate entries in database. Any idea how to control this behaviour?
ReplyDeletegood
ReplyDeleteI wold like to make this upload with the option of delete an image, how can I do This? thanks
ReplyDeletethanks great work
ReplyDeletethanks
ReplyDeletethanks 4 this tutorial.. ur are great ... make lot of other tutorial ok...tq
ReplyDeletegrt wrk
ReplyDeletethanks its good.
ReplyDeletenice work dude
ReplyDeleteNot working on my website its not connecting join.php
ReplyDeleteSorry its working
ReplyDeleteplease with this implement checkbox also for example when I click on checkbox the whole row should be deleted
ReplyDeletethx srinivas for help
ReplyDeleteWhats going wrong with my code ?? Its saving blank entries in my table
ReplyDeleteHtml- http://pastebin.com/4aC3MD36
Php - http://pastebin.com/4wwgGjtj
good work
ReplyDeleteThank you buddy... It was really Really helpful...
ReplyDeleteGood work..
ReplyDeleteisn't this better.
ReplyDeleteMootools:
$('myForm').addEvent('submit', function(e) {
e.stop();
this.set('send', {onComplete: function(response){}});
//send the normal form..
this.send();
});
thanks for helping people like us?
ReplyDeleteHow can we make this code compatible with jQuery 1.7?
ReplyDeleteTons of Thank..for this beautiful tutorial... :D
ReplyDeleteGood Work
ReplyDeleteThanks for your tutorials sir ... very very helping.. and your are really a master of your art and field.. hats off .. :)
ReplyDeletehi , who can i implement this twice in once page for different valuse?? can you give some tutorial for that
ReplyDeleteHai;
ReplyDeleteYou Saved My time..Thanks.
can't upload image with this script help?
ReplyDeletesir,
ReplyDeletei had successfully executed the script after submission (ajax)
how to clear the input field values!
i had done ajax with only with one input text button!
hi
ReplyDeletecan any one give same code for jsp ..actually i am new in JSP and want code to submit form without page refresh..
$('#submit_fourth').click(function(){
ReplyDelete//send information to server
var username = $("#username").val();
var password = $("#password").val();
var email = $("#email").val();
var firstname = $("#firstname").val();
var lasttname = $("#lastname").val();
var age = $("#age").val();
var gender = $("#gender").val();
var country = $("#country").val();
var dataString = 'username='+username + '&password='+ password + '&email='+ email + '&firstname='+firstname + '&age='+ age + '&gender='+gender + '&country='+ country;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "register-exec.php",
data: dataString,
success: function() {
//some msg here
});
}
});
alert( "Data Saved: ");
});
});
Can anyone tell me what is the error in this code? I cant save data in to the database i cant figure it out.
@Shiva Surya
ReplyDeleteI did this, and it works
[code] ...
$.ajax({
type: "POST",
url: "join.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
$('[name="inputName"]').val(''); <-- this part cleans the input
}
...[code]
[email protected]
Brilliant! Just what I needed. I'm a long-time PHP coder but new to AJAX and needed a very simplified example to work through the code and understand it. Other tutorials used more code than was necessary so were more difficult to understand but yours was perfect. Cheers :)
ReplyDeleteHi,
ReplyDeleteI downloaded the scrips and it doesn't execute join.php at all. What's wrong? I entered into join.php code written below
";
?>
plz i need the same + upload file how to do ??
ReplyDeleteNice Thanks For Sharing.
ReplyDeletehi,
ReplyDeletei want to code for get current database datas using php mysql in without refresh page.
can you able to help me.
thanks,
how to get exception from join page, if i have database exception then how cani get error msg from it
ReplyDeleteThanks, I found this really helpful.
ReplyDeleteGod bless.
Try making the source code available to download tho.
Also, one more thing.
ReplyDeleteCan you drop a tutorial on replying comments with Ajax using JQuery, and Php and MySql?
Thank you.
This comment has been removed by a blog administrator.
ReplyDelete