Friday 26 February 2016

Dynamically Add / Remove input fields in PHP with Jquery Ajax







Read Also - How to Edit Dynamic HTML Field by using Ajax with PHP



Hello Friends this tutorial is relating to dynamically insert or delete  input html fields using Jquery Ajax with PHP MySql. User can insert more than one data at the same time. User can Add bulk data at same time. Data will be inserted with out page refresh because we use ajax function call for insert data. User can add more fields by clicking on add more button then new textbox will be appear on webpage with remove button. If user want to remove some field then it can be remove input fields on click on remove button. Now a days this functionality is very useful in web application.










Source Code


index.php


    <html>  
      <head>  
           <title>Dynamically Add or Remove input fields in PHP with JQuery</title>  
           <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
           <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>  
      </head>  
      <body>  
           <div class="container">  
                <br />  
                <br />  
                <h2 align="center">Dynamically Add or Remove input fields in PHP with JQuery</h2>  
                <div class="form-group">  
                     <form name="add_name" id="add_name">  
                          <div class="table-responsive">  
                               <table class="table table-bordered" id="dynamic_field">  
                                    <tr>  
                                         <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>  
                                         <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>  
                                    </tr>  
                               </table>  
                               <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
                          </div>  
                     </form>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      var i=1;  
      $('#add').click(function(){  
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
      });  
      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      });  
      $('#submit').click(function(){            
           $.ajax({  
                url:"name.php",  
                method:"POST",  
                data:$('#add_name').serialize(),  
                success:function(data)  
                {  
                     alert(data);  
                     $('#add_name')[0].reset();  
                }  
           });  
      });  
 });  
 </script>
   

name.php


    <?php  
 $connect = mysqli_connect("localhost", "root", "", "test_db");  
 $number = count($_POST["name"]);  
 if($number > 0)  
 {  
      for($i=0; $i<$number; $i++)  
      {  
           if(trim($_POST["name"][$i] != ''))  
           {  
                $sql = "INSERT INTO tbl_name(name) VALUES('".mysqli_real_escape_string($connect, $_POST["name"][$i])."')";  
                mysqli_query($connect, $sql);  
           }  
      }  
      echo "Data Inserted";  
 }  
 else  
 {  
      echo "Please Enter Name";  
 }  
 ?> 
   

68 comments:

  1. Useful guide! IS there any official PHP tutorial website for learn the new version of cake PHP.
    Regards,
    PHP Training in Chennai|PHP Course in Chennai

    ReplyDelete
    Replies
    1. hai teri chummia aise loon ga ke tu chennai bhool jaye gi ray

      Delete
  2. Hello your demo is interesting but I have a problem how do I do if I want to add 3 fields and once add a message that redirects me to another page thank you in advance this urgent help me please

    ReplyDelete
    Replies
    1. Hi Abdoul Ali, I modified the code and I did what you want, please check it below:

      Delete
  3. Supper Amazing Article....Thanks

    ReplyDelete
  4. Nice post and really cool info about jquery codings.
    Andriod Training Courses in Chennai

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

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

    ReplyDelete
  7. This comment has been removed by a blog administrator.

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

    ReplyDelete
  9. This comment has been removed by a blog administrator.

    ReplyDelete
  10. Nice post and really cool info about jquery codings.
    tib co training in chennai

    ReplyDelete
  11. This comment has been removed by a blog administrator.

    ReplyDelete
  12. how to add all submitted value into a single row name name1 name2 etc it is possible

    ReplyDelete
  13. I am in love with your articles. God bless you

    ReplyDelete
  14. Its not saving data into database giving me this error?
    Notice: Undefined index: name in C:\xampp\htdocs\addfield\name.php on line 3
    Please Enter Name

    ReplyDelete
  15. This tutorial is great! Thank you so much for sharing. Question: how would the script need to be altered if I want to enter more than just one field, for example: firstname, lastname, gender and age?

    ReplyDelete
  16. how can I add more column with existing database.....

    ReplyDelete
  17. Your code is great...thanks for sharing it

    ReplyDelete
  18. How to redirect page after click ok (alert)?

    ReplyDelete
  19. How to redirect page after click ok (alert)?

    ReplyDelete
  20. Your Database is not Working.

    ReplyDelete
  21. Your Database is not working.And I added 6 table but when I cut any one X all table has been remove.

    ReplyDelete
  22. Thanks a bunch,you saved me

    ReplyDelete
  23. Hi. So I used your method to dynamically add my input to the sql database, but I had a hard time updating it. Basically fetching from sql displayed as one input tag per row then will be able to update or delete. Ps. using a modal. Is it possible? TIA

    ReplyDelete
  24. I didnt undersrand this part plase help

    name="name[]"

    ReplyDelete
  25. hello, can u help me if i want to make the input into select button... and the select button will display data from database

    ReplyDelete
  26. if I want to store numbers what to change in the code

    ReplyDelete
  27. not working for php pls help

    ReplyDelete
  28. I think that if you use increment with the add field button, then you should also use decrement with the delete field button. why do I need to add and remove buttons if they are not full.

    ReplyDelete
  29. After reading your blog, I was quite interested to learn more about this information. Thanks for sharing.
    No:1 Best PGDCA Training Center in kanchipuram|

    ReplyDelete
  30. Como fazer ele funcionar com o select2 nos campos adicionais?

    ReplyDelete
  31. hey .its a amazing post.thanks for sharing a great article.keep it up
    www.offsidetech.com

    ReplyDelete
  32. It's interesting that many of the bloggers to helped clarify a few things for me as well as giving.Most of ideas can be nice content.The people to give them a good shake to get your point and across the command. Best MS Office Training Institute In Kanchipuram|

    ReplyDelete
  33. You have made some good points there. I looked on the net for additional information about the issue and found most individuals will go along with your views on this site.
    Tech geek

    ReplyDelete
  34. Very nice blogs!!! I have to learning for lot of information for this sites...Sharing for wonderful information. Thanks for sharing this valuable information to our vision. You have posted a trust worthy blog keep sharing.…
    Matlab Project Center in Chennai |
    Matlab Project Center in Chennai

    ReplyDelete
  35. I would like to get source code of this webslesson.info/2018/03/ajax-crud-on-dynamically-add-remove-input-feilds-in link. Plz advice me or send to my mail.

    ReplyDelete
  36. Thank u for sharing such nice information.!! Total recall is also good one.!! PMP Ceritification in Chennai|

    ReplyDelete
  37. Nice Blog...looking amazing...thank you so much for sharing such a wonderful blog...keep sharing... Best CCNA Certification In Chennai|

    ReplyDelete
  38. this blog is really useful and it is very interesting thanks for sharing , it is really good and exclusive. Best Prince 2 Exam center in chennai|

    ReplyDelete
  39. You are the best. You saved me 2 working days. Thanks!

    ReplyDelete
  40. merci beaucoup pour ce tutoriel

    ReplyDelete
  41. Very happy to see this blog. Gives a wonderful information with coded explanaion. Thank you for this blog. very useful to me. Prince2 Certification Center in Chennai |

    ReplyDelete
  42. This comment has been removed by a blog administrator.

    ReplyDelete
  43. This comment has been removed by a blog administrator.

    ReplyDelete
  44. Great Tutorial.
    Can results from MYSQL while loop be used for new added lines

    ReplyDelete
  45. How to change input field to selection option that can be add and remove

    ReplyDelete
  46. how to change from input text to selection that value get from database and can add and remove

    ReplyDelete
  47. “Great share!” Each and every tips of your post are more informative and it was awesome to read.
    Thank you for such a great post…..

    ReplyDelete
  48. if someone click on add button and fill only the first form still it is getting submitted to database after clicking the submit button how can i make it mandatory to fill the extra form too

    ReplyDelete
  49. Nice blog. I feel really happy to have seen your web page and look forward to so many more amusing times reading here. Thanks once more for all the details.
    PythonFullStack training in Chennai
    PythonFullStack training in Velachery
    PythonFullStack training in Thambaram
    PythonFullStack training in Guindy
    PythonFullStack training in Tharamani

    ReplyDelete