Wednesday, 25 October 2017

Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP



Sometimes we want to required add or remove dynamic html fields in a form. We have already seen how to add or remove simple html input fields dynamically in a form, but how to add or remove dynamic select box into form dynamically. So We have make this simple tutorial to learn how can we add or remove select box data dynamically using Jquery and how can we insert multiple select box data into Mysql table by using Ajax with PHP without refresh of webpage.

For Add or remove drop down list box data dynamically into form, we have developed a jquery script by using script we can add or remove multiple select box fields very easily. In this script also useful for insert multiple values of drop down list box in PHP by using Ajax. In this post we have discuss how to generate dynamic select box HTML fields in a form while filling of form and after adding multiple select box data into the database. For this we have used Jquery to developed this type of functionality with very short, simple and powerful. By using this script we can add or remove dynamic select box fields very easily. After adding multiple select box fields and submit those select box value into PHP script by using Ajax and inserted into Mysql table.

In this post to learn how to add or remove dynamic Select Box data dynamically using Jquery and insert into Mysql table using Ajax with PHP. So Here we have make simple invoice script for add multiple item data into single order. In this example Item name and Quantity data has been insert into text box field but for enter Item Unit data we have use dynamic select box. So here we have use dynamic drop down list box for enter Item unit data and here when we have add one more item then this dynamic select box with filled data has been generated for select Item unit value. Here Add or remove of input fields with dynamic drop down list box code has been generated by using Jquery script. After adding and removing all item details we will insert multiple item data with dynamic select box data into Mysql table by using Ajax with PHP, so here data multiple data will be inserted without refresh of web page.




Source Code


index.php



<?php
//index.php

$connect = new PDO("mysql:host=localhost;dbname=testing4", "root", "");
function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM tbl_unit ORDER BY unit_name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["unit_name"].'">'.$row["unit_name"].'</option>';
 }
 return $output;
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <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.7/js/bootstrap.min.js"></script>
 </head>
 <body>
  <br />
  <div class="container">
   <h3 align="center">Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</h3>
   <br />
   <h4 align="center">Enter Item Details</h4>
   <br />
   <form method="post" id="insert_form">
    <div class="table-repsonsive">
     <span id="error"></span>
     <table class="table table-bordered" id="item_table">
      <tr>
       <th>Enter Item Name</th>
       <th>Enter Quantity</th>
       <th>Select Unit</th>
       <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
      </tr>
     </table>
     <div align="center">
      <input type="submit" name="submit" class="btn btn-info" value="Insert" />
     </div>
    </div>
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $(document).on('click', '.add', function(){
  var html = '';
  html += '<tr>';
  html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
  html += '<td><input type="text" name="item_quantity[]" class="form-control item_quantity" /></td>';
  html += '<td><select name="item_unit[]" class="form-control item_unit"><option value="">Select Unit</option><?php echo fill_unit_select_box($connect); ?></select></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
  $('#item_table').append(html);
 });
 
 $(document).on('click', '.remove', function(){
  $(this).closest('tr').remove();
 });
 
 $('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.item_name').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Name at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_quantity').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Item Quantity at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.item_unit').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Select Unit at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#item_table').find("tr:gt(0)").remove();
      $('#error').html('<div class="alert alert-success">Item Details Saved</div>');
     }
    }
   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});
</script>


insert.php



<?php
//insert.php;

if(isset($_POST["item_name"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=testing4", "root", "");
 $order_id = uniqid();
 for($count = 0; $count < count($_POST["item_name"]); $count++)
 {  
  $query = "INSERT INTO tbl_order_items 
  (order_id, item_name, item_quantity, item_unit) 
  VALUES (:order_id, :item_name, :item_quantity, :item_unit)
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':order_id'   => $order_id,
    ':item_name'  => $_POST["item_name"][$count], 
    ':item_quantity' => $_POST["item_quantity"][$count], 
    ':item_unit'  => $_POST["item_unit"][$count]
   )
  );
 }
 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'ok';
 }
}
?>


Database



--
-- Database: `testing4`
--

-- --------------------------------------------------------

--
-- Table structure for table `tbl_order_items`
--

CREATE TABLE IF NOT EXISTS `tbl_order_items` (
  `order_items_id` int(11) NOT NULL,
  `order_id` varchar(150) NOT NULL,
  `item_name` varchar(250) NOT NULL,
  `item_quantity` int(11) NOT NULL,
  `item_unit` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- --------------------------------------------------------

--
-- Table structure for table `tbl_unit`
--

CREATE TABLE IF NOT EXISTS `tbl_unit` (
  `unit_id` int(11) NOT NULL,
  `unit_name` varchar(250) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_unit`
--

INSERT INTO `tbl_unit` (`unit_id`, `unit_name`) VALUES
(1, 'Bags'),
(2, 'Bottles'),
(3, 'Box'),
(4, 'Dozens'),
(5, 'Feet'),
(6, 'Gallon'),
(7, 'Grams'),
(8, 'Inch'),
(9, 'Kg'),
(10, 'Liters'),
(11, 'Meter'),
(12, 'Nos'),
(13, 'Packet'),
(14, 'Rolls');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_order_items`
--
ALTER TABLE `tbl_order_items`
  ADD PRIMARY KEY (`order_items_id`);

--
-- Indexes for table `tbl_unit`
--
ALTER TABLE `tbl_unit`
  ADD PRIMARY KEY (`unit_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_order_items`
--
ALTER TABLE `tbl_order_items`
  MODIFY `order_items_id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `tbl_unit`
--
ALTER TABLE `tbl_unit`
  MODIFY `unit_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=15;

40 comments:

  1. Very Nice article but how can we edit form on same way

    ReplyDelete
  2. How to show submited data in same form

    ReplyDelete
  3. server side add more button not working plz help me

    ReplyDelete
  4. Thank you for this code. Here i need something like all the three are select boxes. So i'm trying to write three functions and returning the values.But it's not working. Can you please help me out??

    ReplyDelete
  5. where should i change the code to get id from selected unitname option box and save the id to database?? btw thanks for the tutorial.

    ReplyDelete
  6. Can you please post mysqli procedural version of insert.php..

    ReplyDelete
  7. Hello
    Good job, congratulations
    but when I put another drop-down list with another table, I can not add rows anymore, the adding procedure does not go
    Have a good day

    ReplyDelete
  8. lists do not display when there are too many records to load (200 to 500)

    ReplyDelete
  9. Hi,in this code java script is not working for alert.Please give solution.

    ReplyDelete
  10. a small error in the verification...
    just define the count variable before the loop.

    ReplyDelete
  11. i have a unique problem.can we do this without serialize method? can we use different method? and i dont know syntax of PDO so can you send me a backend file with simple mysql code.i search a lot of vedio.everyone is doing with pdo and serialize.i am ok with serialize but not with pdo my id is "mangla.vishu@gmail.com"

    ReplyDelete
  12. please make one demo for codeigniter

    ReplyDelete
  13. Hi Sir
    this is awesome, works on WAMP server perfect but not IIS 7.5 shows error 500, Please Advise

    ReplyDelete
  14. Hi sir,
    in dreamweaver it works perfectly,but when i try to run in localhost xampp it doesnt show the javascript function.

    ReplyDelete
  15. nothing is happening on click of the insert button

    ReplyDelete
  16. hye do you have sample for cakephp?

    ReplyDelete
  17. how to update the table rows

    ReplyDelete
  18. why i cannot click the submit button?

    ReplyDelete
    Replies
    1. Did Submit button work after some change??

      Delete
  19. How can I get the selected id of the Select and place it on the next textfield?

    ReplyDelete
  20. Hi, thank you for the tutorial but what can i do if i want to insert data in two different tables on MYQSL database, please help.

    ReplyDelete
  21. this perfectly tutorial, thanks..

    ReplyDelete
  22. its not working .php its wokring only .html feli why???

    ReplyDelete
  23. its not working .php its wokring only .html feli why???

    ReplyDelete
  24. I need same table with an image input field. Can you pls help me?

    ReplyDelete
  25. how can you insert an image file for this code cab somebody help me

    ReplyDelete
  26. can i get source code ?

    ReplyDelete
  27. if these select box value depends on another select box.then what to do?

    ReplyDelete
  28. hye, nothing is happening on click of the insert button , can you help me

    ReplyDelete
  29. please make one demo for codeigniter also

    ReplyDelete
  30. How I can Show the Item Name details in a list

    ReplyDelete
  31. This is working fine if only one select fields value are showing from database. if we have more than two select field value like countries and university data in separate select fields than its not working. I have made two functions for countries and university and try to show its data from database but its not working. Can you please let me know how can i fix this?

    ReplyDelete
  32. please how do i make the select to be searchable

    ReplyDelete