Submit a Form without Refreshing page with jQuery and Ajax.
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

86 comments:

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

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

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

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

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

    ReplyDelete
  5. hi. why dont use Jquery form Plugin?

    ReplyDelete
  6. @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 ?

    ReplyDelete
  7. isn't this better.

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

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

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

    ReplyDelete
  9. Heey great tutorial! :D

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

    Keep up the good work!!

    ReplyDelete
  10. how can i add the loading image while processing?

    ReplyDelete
  11. 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

    ReplyDelete
  12. 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.

    ReplyDelete
  13. This comment has been removed by the author.

    ReplyDelete
  14. 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.

    ReplyDelete
  15. Hi Tim,

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

    ReplyDelete
  16. 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.

    ReplyDelete
  17. Hello Tim,

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


    Srinivas Tamada

    ReplyDelete
  18. 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.

    ReplyDelete
  19. Hi Sam Bennett

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

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

    ReplyDelete
  21. 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!!!!

    ReplyDelete
  22. Nope, wont work with the current jquery

    ReplyDelete
  23. 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.

    ReplyDelete
  24. 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...

    ReplyDelete
  25. 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.

    ReplyDelete
  26. 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

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

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

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

    ReplyDelete
  29. 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.

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

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

    I have a question:

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

    Thanx

    ReplyDelete
  32. 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

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

    ReplyDelete
  34. 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!

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

    ReplyDelete
  36. 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!

    ReplyDelete
  37. 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

    ReplyDelete
  38. hi,

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

    Thanks

    ReplyDelete
  39. Real Great Tutorial. Thanks Guys

    Deji

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

    Please help...

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

    ReplyDelete
  42. 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!

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

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

    ReplyDelete
  45. thanks great work

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

    ReplyDelete
  47. Not working on my website its not connecting join.php

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

    ReplyDelete
  49. thx srinivas for help

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

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

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

    ReplyDelete
  52. isn't this better.

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

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

    ReplyDelete
  53. thanks for helping people like us?

    ReplyDelete
  54. How can we make this code compatible with jQuery 1.7?

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

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

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

    ReplyDelete
  58. Hai;

    You Saved My time..Thanks.

    ReplyDelete
  59. can't upload image with this script help?

    ReplyDelete
  60. 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!

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

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

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

    ReplyDelete
  64. 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 :)

    ReplyDelete
  65. 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

    ";
    ?>

    ReplyDelete
  66. plz i need the same + upload file how to do ??

    ReplyDelete