9lessons programming blog
Loading Search
9lessons Bring Friends
Wall Script
Follow Me:
Wednesday, April 22, 2009

Submit a Form without Refreshing page with jQuery and Ajax.

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>



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&gt;

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
Comments
{ 84 comments }
Anonymous said...

Easier: var data=$('#theform').serialize();

Anonymous said...

Hello I just tried it on my website but it came out with an error saying : Method Not Allowed
The 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 ?

Srinivas Tamada said...

Wrong:
url: "/file/join.php"

Write:
url: "http://domain.com/file/join.php"

Anonymous said...

There are some excellent jQuery plugins for this.
No need to reinvent the wheel.

Anonymous said...

hi. why dont use Jquery form Plugin?

Charlie said...

Why not build your own?

Anonymous said...

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

What about the SQL query ?

nocturnal said...

isn't this better.

Mootools:
$('myForm').addEvent('submit', function(e) {

e.stop();
this.set('send', {onComplete: function(response){}});
//send the normal form..
this.send();
});

Anonymous said...

@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).

Johnie Webdesign said...

Heey great tutorial! :D

One thing, can you maybe add a emailvalidation for this script?:)

Keep up the good work!!

Anonymous said...

vgf

ahmed said...

how can i add the loading image while processing?

ahmed said...

what's wrong with code? , when i press send button it just reload the page, it didn't perform any function or query?

please replay to me

Srinivas Tamada said...

Did u link with jQuery plug-in

Tim said...

Hello, 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.

Tim said...
This comment has been removed by the author.
Tim said...

I'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).

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

Srinivas Tamada said...

Hi Tim,

Send your files to my email id: srinivas@inbox.com

Tim said...

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.

Srinivas Tamada said...

Hello Tim,

I did not get any mail your side- send to srinivas@inbox.com or sinu@zenbe.com


Srinivas Tamada

Sam Bennett said...

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.

Srinivas Tamada said...

Hi Sam Bennett

Take a look at this link http://9lessons.blogspot.com/2009/06/comment-system-with-jquery-ajax-and-php.html

Anonymous said...

useful

Anonymous said...

Im using your code with CMS system
the 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 ?

Anonymous said...

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

Fan in Nigeria!!!!

Srinivas Tamada said...

Thank You Nigeria

test said...

bfd

trikks said...

Nope, wont work with the current jquery

Anonymous said...

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

Anonymous said...

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

Dere said...

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

Dere said...

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

Thanks Again,
Derek

Anonymous said...

Hi nice tutorial thanks, I was wondering how to add the recipient email address. any help would be appreciated

Anonymous said...

as others have said there is plugins that do all this for you

http://jquery.malsup.com/form/#getting-started

Anonymous said...

Hi,
I 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.

sankar said...

Hi,
your code is good. But
I just tried array of form data, so how can i change this code.
please help me

keerthi teja said...

Hi srinivas....:)
Great tutorial again..

I have a question:

After submiting i want clear the textfield.
how to do that...???
plz Help

Thanx

keerthiteja said...

To clear textfields after submitting:

$('#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

Anonymous said...

Hi srinivas....:)
Great tutorial again..

Anonymous said...

Hello I am curious to know what the solution to using multiple forms on one page, each with their own submit and unique IDs.

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

taran said...

nice

kim said...

Hi.

I´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?

vynnus said...

Thank you so much for this script!

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

vish said...

thanx boss

Anonymous said...

What if I wanted to submit the form to send an email instead.

The form in question only has one field and here is the php I used:



Thanks

Anonymous said...

hi,

How could i do the same with a file? Is it possible to Submit a Form with a file without Refreshing page?

Thanks

Anonymous said...

Real Great Tutorial. Thanks Guys

Deji

Anonymous said...

hi
good

Hamid Mahmood said...

What if your sql insert failed and you want to display the error which you have received from the database server.

Please help...

monk said...

i cant get work ratio.
is shows always a first parametr. Anyone else the same ? thanks

Anonymous said...

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

Anonymous said...

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?

Anonymous said...

good

Anonymous said...

I wold like to make this upload with the option of delete an image, how can I do This? thanks

Anonymous said...

thanks great work

Anonymous said...

thanks

Anonymous said...

thanks 4 this tutorial.. ur are great ... make lot of other tutorial ok...tq

Diundi said...

grt wrk

robin said...

thanks its good.

Anonymous said...

nice work dude

Yasir Malik said...

Not working on my website its not connecting join.php

Yasir Malik said...

Sorry its working

kishore kumar said...

please with this implement checkbox also for example when I click on checkbox the whole row should be deleted

Anonymous said...

thx srinivas for help

saurabh said...

Whats going wrong with my code ?? Its saving blank entries in my table

Html- http://pastebin.com/4aC3MD36
Php - http://pastebin.com/4wwgGjtj

Anonymous said...

good work

Anonymous said...

Thank you buddy... It was really Really helpful...

Anonymous said...

Good work..

sameer md said...

isn't this better.

Mootools:
$('myForm').addEvent('submit', function(e) {

e.stop();
this.set('send', {onComplete: function(response){}});
//send the normal form..
this.send();
});

Anonymous said...

thanks for helping people like us?

Unknown said...

How can we make this code compatible with jQuery 1.7?

Anonymous said...

Tons of Thank..for this beautiful tutorial... :D

Anonymous said...

Good Work

Anonymous said...

Thanks for your tutorials sir ... very very helping.. and your are really a master of your art and field.. hats off .. :)

My first Blog said...

hi , who can i implement this twice in once page for different valuse?? can you give some tutorial for that

Aeton said...

Hai;

You Saved My time..Thanks.

Anonymous said...

can't upload image with this script help?

Shiva Surya said...

sir,
i 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!

SNEHA said...

hi
can any one give same code for jsp ..actually i am new in JSP and want code to submit form without page refresh..

Anonymous said...

$('#submit_fourth').click(function(){
//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.

Anonymous said...

@Shiva Surya

I 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]

guimaraesmvf@hotmail.com

Karthick M said...

very nice

Dan said...

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

Marcin Kopeć said...

Hi,
I downloaded the scrips and it doesn't execute join.php at all. What's wrong? I entered into join.php code written below

";
?>

Post a Comment