Submit PHP Form without Page Refresh using jQuery, Ajax | Coding Cage

Submit PHP Form without Page Refresh using jQuery, Ajax

By
In today's tutorial i am going to share the most useful jQuery functions $.ajax() and $.post(), using these two functions you can submit the PHP Web Forms without Refreshing the whole Web Page of Your Site, The jQuery get() and post() methods are used to request data from the server with an HTTP GET or POST request, hence $.post() function is a Shorthand Ajax method, so this tutorial will guide you that how to use jQuery's $.ajax() and $.post() functions easily to submit PHP Form Data to the Server Web Page without Refreshing the Page, let's see it in detail.
Submit PHP Form without Page Refresh using jQuery, Ajax
 

for this tutorial i have created here a simple HTML form which will take some inputs from the user , first name, last name, email id and contact no, below form is in div tag which have id and class attributes to perform jQuery effects.

Simple HTML Form :

Simple HTML Form created with bootstrap so it looks better and some inputs i have used here to pass the entered values in another file via ajax.

<div id="form-content">
     <form method="post" id="reg-form" autocomplete="off">
   
 <div class="form-group">
 <input type="text" class="form-control" name="txt_fname" id="lname" placeholder="First Name" required />
 </div>
    
 <div class="form-group">
 <input type="text" class="form-control" name="txt_lname" id="lname" placeholder="Last Name" required />
 </div>
    
 <div class="form-group">
 <input type="text" class="form-control" name="txt_email" id="lname" placeholder="Your Mail" required />
 </div>
    
 <div class="form-group">
 <input type="text" class="form-control" name="txt_contact" id="lname" placeholder="Contact No" required />
 </div>
    
 <hr />
    
 <div class="form-group">
 <button class="btn btn-primary">Submit</button>
 </div>
    
    </form>     
</div>






Files we need

guys i have used bootstrap for the design so add the following style sheet and javascript files.
Add Bootstrap CSS file
<link rel="stylesheet" href="assets/css/bootstrap.min.css">

Add JavaScript/jQuery files
<script src="assets/jquery-1.12.4-jquery.min.js"></script>
<script src="assets/js/bootstrap.min.js"></script>

Submitting Form via Ajax :

$.ajax() is a super and flexible method to pass the form values to another page by requesting back-end php file, so here in this example i have created submit.php file it will handles the ajax request silently with HTTP POST Request, and using "serialize()" you can easily merge data of forms.
$('#reg-form').submit(function(e){
  
    e.preventDefault(); // Prevent Default Submission
  
    $.ajax({
 url: 'submit.php',
 type: 'POST',
 data: $(this).serialize(), // it will serialize the form data
        dataType: 'html'
    })
    .done(function(data){
     $('#form-content').fadeOut('slow', function(){
          $('#form-content').fadeIn('slow').html(data);
        });
    })
    .fail(function(){
 alert('Ajax Submit Failed ...'); 
    });
});

submit.php

as i said data will be posted via submit.php file, so here is the file with simple mixed php and html code and displayed within index file without page refresh, it will accepts data via $.ajax() call and display the results in "index.php" file.

<?php

if( $_POST ){
 
    $fname = $_POST['txt_fname'];
    $lname = $_POST['txt_lname'];
    $email = $_POST['txt_email'];
    $phno = $_POST['txt_contact'];

    ?>
    
    <table class="table table-striped" border="0">
    
    <tr>
    <td colspan="2">
     <div class="alert alert-info">
      <strong>Success</strong>, Form Submitted Successfully...
     </div>
    </td>
    </tr>
    
    <tr>
    <td>First Name</td>
    <td><?php echo $fname ?></td>
    </tr>
    
    <tr>
    <td>Last Name</td>
    <td><?php echo $lname ?></td>
    </tr>
    
    <tr>
    <td>Your eMail</td>
    <td><?php echo $email; ?></td>
    </tr>
    
    <tr>
    <td>Contact No</td>
    <td><?php echo $phno; ?></td>
    </tr>
    
    </table>
    <?php
 
}

Using $.post() : Ajax short hand method

Here is the short and simple code which can do the same as above using $.post() method. well it's a ajax short hand method for submitting forms in short and simple way, have a look.
$('#reg-form').submit(function(e){
  
    e.preventDefault(); // Prevent Default Submission
  
    $.post('submit.php', $(this).serialize() )
    .done(function(data){
      $('#form-content').fadeOut('slow', function(){
          $('#form-content').fadeIn('slow').html(data);
        });
    })
    .fail(function(){
     alert('Ajax Submit Failed ...');
    });
});

that's it, here how you can easily submit forms using jQuery without Page Refresh, well this is just for beginners to show how forms data can be pass through the jQuery, we will see complete crud tutorial on jQuery CRUD very soon, hope you like it.



50 comments:

  1. thanks for post. its help full. http://manirulislamcse.blogspot.com/

    ReplyDelete
  2. can be use this script for multiple forms in same page?

    ReplyDelete
    Replies
    1. Hi Daniel ,

      Yes you can use this script for multiple forms in same page by giving different id in forms

      Delete
    2. Great, but what changes should I make in javascript code? I assume that for now it reacts only if #reg-form is submited

      Delete
    3. and how to change javascript code if I would like to edit about 100-200records (each in separate form), I assume that for now it reacts only on submitting #reg-form

      Delete
    4. hello mario, yes this code reacts only for one form which has #reg-form id, if you want to submit multiple form then you have to create multiple forms and give them different id

      form1 = #form1

      $(document).on('submit', '#form1', function()
      {

      });

      form2 = #form2

      $(document).on('submit', '#form2', function()
      {

      });

      Delete
    5. so if I want to put about 100 such forms on my site I need to copy 100x the javascript code? hmm, no thanks :(

      Delete
    6. use PHP loop for your form an the script

      Delete
  3. Hi, this is great works brilliant but what if you have a JQuery validation method in place? this skips the validation and sends the form?

    ReplyDelete
    Replies
    1. Yes , I just want to show that how you can submit forms using jQuery for validations try following link

      Simple jQuery Validation

      Delete
  4. Thanks for this awesome script...
    and keep posting... :)

    ReplyDelete
  5. Nice blog...Very useful information is providing by ur blog. Great beginning php tutorials Very clear and helpful for beginners.

    ReplyDelete
  6. Hi, this is great works brilliant Pradeep Khodke..
    Thanks for this awesome post...
    and keep posting... :)

    ReplyDelete
    Replies
    1. hello anil,
      thanks for such a nice comment,
      glad you liked it and keep visiting :)

      Delete
  7. Hi Pradeep!!! Very nice tutorial. But I am facing a problem, refreshing the submitted page goes back to form. I want it to retain on the result page. Please guide me to do so.
    Thanks.

    ReplyDelete
    Replies
    1. Hello sandeep, please be detailed about your query, i didn't get you. here in this tutorial submitted pages result actually displayed in another page but using jquery i showed them within same page("index.php").

      Delete
    2. Actually I want the result and form after submit. It shows result only but after refreshing the same page returns form.

      Delete
  8. Helo Khodke...Download link is not functioning,there for i cant download this script.

    ReplyDelete
  9. Hi, im using this jquery/ Javascript code only, after submit the form, everything works fine but i cant display the result. can u say the solution?

    ReplyDelete
  10. nice tuto can you fix link of download sources.

    ReplyDelete
  11. Nices tuto can you fix the link to download a example. thanks

    ReplyDelete
  12. Nice piece of code, but the download link is not working...Thanks

    ReplyDelete
    Replies
    1. Hello Tobiloba, link was updated you can download it now

      Delete
  13. hi sir thanks a lot your site helped me very much.I am a begineer in web developing and have some confusions but your site solved my problem

    ReplyDelete
    Replies
    1. Hello Piyush,
      thanks for the valuable comment, this inspires me to keep posting tutorials for beginners, and sorry for the late reply actually i have lot's of pending comments and it's hard to answer each and every one.

      Delete
  14. hi thanks a lot yout site helped me very much. i would task you how to add a butum to add the information in my database in the seconde form

    ReplyDelete
  15. Pradip You are doing really great ...!I was searching it from Long time ,And Here I found It.

    Thanks
    Regards
    Ravindra Solanki
    www.hackersdenabi.net

    ReplyDelete
  16. Hey! Great works :) Thanks for this awesome blog :*

    ReplyDelete
  17. I`m adding button "Add more" with href="index.php". Can you help me how do redirecting wiht ajax to page with form? Thanks

    ReplyDelete
    Replies
    1. hello sergiy...

      your can load any page within particular div, with "load('pagename.php')" function

      this might help you :

      http://www.codingcage.com/2015/12/simple-jquery-insert-update-delete-with.html

      Delete
    2. how to ajax view file with refreshing page don't hide page

      Delete
  18. I'm sorry to ask, but where do I put my mail in this script?

    ReplyDelete
  19. hello sir pradeep. i altered the submit form to insert the data in my table. but when i clicked the submit button 2 times or more it inserted 2 times/or more rows in my table.

    eg.
    query=insert into users (username)values('USERTEST1');

    my table users will look like this.
    userid username
    1 USERTEST1
    2 USERTEST2

    ReplyDelete
    Replies
    1. Hi Ravenreaving
      for that you have to disable submit button when form is submitting and enable it again after form is submitted... like this ...

      $('#reg-form').submit(function(e){

      e.preventDefault(); // Prevent Default Submission
      $('form :submit').prop('disabled', true); // disable submit button
      $.ajax({
      // ajax source
      })
      .done(function(data){
      $('form :submit').prop('disabled', false); // enable submit button
      })
      .fail(function(){
      alert('Ajax Submit Failed ...');
      });
      });



      that's it...

      Delete
  20. hey the download button, doesn't work

    ReplyDelete
  21. hi i need help, i can't download the files :(

    ReplyDelete
  22. I subscribed, but not able to download at all. It keeps saying, mail not found!

    ReplyDelete
  23. I was trying to download the script but It just keep on refusing my request. I subscribed, and still no success to get my hands on the script.
    I hope you can help me get the fix as I really need to check out this brilliant codes. I really feel that it will solve the issue I am having with my page. Thanks.

    ReplyDelete
  24. I was trying to download the script but It just keep on refusing my request. I subscribed, and still no success to get my hands on the script.
    I hope you can help me get the fix as I really need to check out this brilliant codes. I really feel that it will solve the issue I am having with my page. Thanks.

    ReplyDelete
  25. Thanks for providing this informative information…..
    You may also refer-
    http://www.s4techno.com/blog/category/application/php/

    ReplyDelete
  26. what if i have multiple methods in my Submit.php, how can I know where the request came from?

    ReplyDelete
  27. hi >> this the very very good ... but i`m get problem ... when get the code on my page and run page .. when enter to Submit button will referch page and get data >> i`m not want to referch page >> plase help me in fast ,,,,

    ReplyDelete
  28. Hello, how I put the mail to send the form info?

    ReplyDelete
    Replies
    1. HI Eliaquim, just use PHPMailer, i'll post a tutorial on it.

      Delete