Showing posts with label add more fields. Show all posts
Showing posts with label add more fields. Show all posts

Monday, 16 September 2019

Add or Remove Dynamic Dependent Select Box using jQuery with PHP Ajax

Part - 1




Part - 2




Part - 3




This is one more post on Add or Remove Input field, but now here we will discuss, how to Add or Remove Dynamic Dependent Select Box input field by using jQuery and How to insert Multiple input field data into Mysql table by using PHP with Ajax. Dynamic Dependent Select box or Drop down list box means child select box data must be depend on the value of select in parent select box. When we have change the value of parent select box then child select box data will be automatically change.

In some of our previous tutorial, we have already discuss how to Add or remove text box input field using jQuery with Ajax and PHP and we have also seen how to add or remove dynamic select box input field data using jQuery Ajax and PHP. But now question arise how to insert multiple form data with field like dynamic dependent select box. For this type of data we have to use add or remove input field using jQuery.

Currently, we have seen in PHP web development, in many event in which we want to insert multiple data into mysql database. Then at that time we would to require add or remove input fields concept. This feature has been used mainly used for multiple data insert into mysql table. But suppose in multiple data, we want to process dynamic dependent select box data, then at that time one question arise can we solve the problem of processing of multiple dynamic dependent select box data with add or remove input field concept. Below you can find complete source code for add or remove dynamic dependent select box using jquery and insert multiple input fields data using ajax with php.









Source Code


Mysql Table Stucture



--
-- Database: `testing`
--

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

--
-- Table structure for table `tbl_category`
--

CREATE TABLE `tbl_category` (
  `category_id` int(11) NOT NULL,
  `category_name` varchar(200) NOT NULL,
  `parent_category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Dumping data for table `tbl_category`
--

INSERT INTO `tbl_category` (`category_id`, `category_name`, `parent_category_id`) VALUES
(2, 'Chemicals', 0),
(3, 'Inorganic chemicals', 2),
(4, 'Organic Chemicals', 2),
(5, 'Electronics', 0),
(6, 'Laptop', 5),
(7, 'Dell', 6),
(8, 'i3 Processor', 7),
(9, 'i5 Processors', 7),
(10, 'i7 Processors', 7),
(11, 'Epoxy', 2),
(12, 'Fine Chemicals', 2),
(13, 'Mobile', 5),
(14, 'Sensors', 5),
(15, 'Food', 0),
(16, 'Textile', 0),
(17, 'Fruits', 15),
(18, 'Vegetables', 15),
(19, 'Safety Shoes', 16),
(20, 'Uniform', 16);

--
-- Indexes for dumped tables
--

--
-- Indexes for table `tbl_category`
--
ALTER TABLE `tbl_category`
  ADD PRIMARY KEY (`category_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `tbl_category`
--
ALTER TABLE `tbl_category`
  MODIFY `category_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;

-------

--
-- Table structure for table `items`
--

CREATE TABLE `items` (
  `item_id` int(11) NOT NULL,
  `item_name` varchar(250) NOT NULL,
  `item_category_id` int(11) NOT NULL,
  `item_sub_category_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

--
-- Indexes for table `items`
--
ALTER TABLE `items`
  ADD PRIMARY KEY (`item_id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `items`
--
ALTER TABLE `items`
  MODIFY `item_id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;


database_connection.php



<?php

//database_connection.php

$connect = new PDO("mysql:host=localhost; dbname=testing;", "root", "");

function fill_select_box($connect, $category_id)
{
 $query = "
  SELECT * FROM tbl_category 
  WHERE parent_category_id = '".$category_id."'
 ";

 $statement = $connect->prepare($query);

 $statement->execute();

 $result = $statement->fetchAll();

 $output = '';

 foreach($result as $row)
 {
  $output .= '<option value="'.$row["category_id"].'">'.$row["category_name"].'</option>';
 }

 return $output;
}

?>


index.php



<?php

//index.php

include('database_connection.php');

?>

<!DOCTYPE html>
<html>
  <head>
    <title>Add Remove Dynamic Dependent Select Box using Ajax jQuery with 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 Dynamic Dependent Select Box using Ajax jQuery with 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">
            <thead>
              <tr>
                <th>Enter Item Name</th>
                <th>Category</th>
                <th>Sub Category</th>
                <th><button type="button" name="add" class="btn btn-success btn-xs add"><span class="glyphicon glyphicon-plus"></span></button></th>
              </tr>
            </thead>
            <tbody></tbody>
          </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(){
      
      var count = 0;

      $(document).on('click', '.add', function(){
        count++;
        var html = '';
        html += '<tr>';
        html += '<td><input type="text" name="item_name[]" class="form-control item_name" /></td>';
        html += '<td><select name="item_category[]" class="form-control item_category" data-sub_category_id="'+count+'"><option value="">Select Category</option><?php echo fill_select_box($connect, "0"); ?></select></td>';
        html += '<td><select name="item_sub_category[]" class="form-control item_sub_category" id="item_sub_category'+count+'"><option value="">Select Sub Category</option></select></td>';
        html += '<td><button type="button" name="remove" class="btn btn-danger btn-xs remove"><span class="glyphicon glyphicon-minus"></span></button></td>';
        $('tbody').append(html);
      });

      $(document).on('click', '.remove', function(){
        $(this).closest('tr').remove();
      });

      $(document).on('change', '.item_category', function(){
        var category_id = $(this).val();
        var sub_category_id = $(this).data('sub_category_id');
        $.ajax({
          url:"fill_sub_category.php",
          method:"POST",
          data:{category_id:category_id},
          success:function(data)
          {
            var html = '<option value="">Select Sub Category</option>';
            html += data;
            $('#item_sub_category'+sub_category_id).html(html);
          }
        })
      });

      $('#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_category').each(function(){
          var count = 1;

          if($(this).val() == '')
          {
            error += '<p>Select Item Category at '+count+' row</p>';
            return false;
          }

          count = count + 1;

        });

        $('.item_sub_category').each(function(){

          var count = 1;

          if($(this).val() == '')
          {
            error += '<p>Select Item Sub category '+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>


fill_sub_category.php



<?php

//fill_sub_category.php

include('database_connection.php');

echo fill_select_box($connect, $_POST["category_id"]);

?>


insert.php



<?php

//insert.php;

if(isset($_POST["item_name"]))
{
 include('database_connection.php');

 for($count = 0; $count < count($_POST["item_name"]); $count++)
 {
  $data = array(
   ':item_name'   => $_POST["item_name"][$count],
   ':item_category_id'  => $_POST["item_category"][$count],
   ':item_sub_category_id' => $_POST["item_sub_category"][$count]
  );

  $query = "
   INSERT INTO items 
       (item_name, item_category_id, item_sub_category_id) 
       VALUES (:item_name, :item_category_id, :item_sub_category_id)
  ";

  $statement = $connect->prepare($query);

  $statement->execute($data);
 }

 echo 'ok';
}


?>



Saturday, 5 May 2018

AngularJS | Add Remove Input Fields Dynamically in PHP




In this post We would like to share you How can we implement add more and remove dynamic textbox or input fields by using AngularJS with PHP language. By using this sourcecode anybody can adding or removing form fields dynamically and after this save or insert that fields data into Mysql database by using PHP script. If you have not know How to dynamically add or remove HTML input fields by using Angular javascript then this tutorial is for you in which we have describe step by step How to use AngularJS code for make form with add or remove dynamic HTML input fields and after this we have describe how to save dynamic fields data by using PHP PDO.

If in our web project which we have build with AngularJS as frontend and in backend we have use PHP and in that we want to required add dynamic input fields then you have come on right place. Under this tutorial you can find full source code for add or remove input fields dynamically by using AngularJS and by using PHP with AngularJS we have insert that dynamic input fields data into mysql database. In this tutorial we have make following files.

  • index.html
  • database_connection.php
  • fetch_data.php
  • insert.php

So if you want to learn how to add or remove input fields dynamically in AngularJS with PHP. So you have to just follow this tutorial step by step.









index.php


First we have create simple index.html file in which we have already include bootstrap and AngularJS library. In this file we have write html code for display alert message by using bootstrap, create form with add or remove dynamic input fields and below form we have make on table for display inserted data. In this file we have also write Angular javascript code for fetch data from mysql table, add one more input fields, remove input fields and lastly we have make function for submit form data PHP script.


<!DOCTYPE html>
<html>
 <head>
  <title>AngularJS | Add Remove Input Fields Dynamically in PHP</title>
  <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
 </head>
 <body>
  <br />
   <h3 align="center">AngularJS | Add Remove Input Fields Dynamically in PHP</h3>
  <br />
  <div ng-app="dynamicApp" ng-controller="dynamicController" class="container" style="width:600px;" ng-init="fetchData()">
   
   <div class="alert alert-success alert-dismissible" ng-show="success" >
    <a href="#" class="close" aria-label="close">&times;</a>
    {{successMessage}}
   </div>

   <div class="alert alert-danger alert-dismissible" ng-show="error" >
    <a href="#" class="close" aria-label="close">&times;</a>
    {{errorMessage}}
   </div>

   <form method="post" ng-submit="submitForm()">
    <div class="form-group">
     <label>Enter Your Name</label>
     <input type="text" name="name" id="name" ng-model="formData.person_name" class="form-control" />
    </div>
    <fieldset ng-repeat="row in rows">
     <div class="form-group">
      <label>Enter Your Programming Skill</label>
      <div class="row">
       <div class="col-md-9">
        <input type="text" name="programming_languages[]" class="form-control" ng-model="formData.skill[$index + 1]" />
       </div>
       <div class="col-md-3">
        <button type="button" name="remove" ng-model="row.remove" class="btn btn-danger btn-sm" ng-click="removeRow()"><span class="glyphicon glyphicon-minus"></span></button>
       </div>
      </div>
     </div>
    </fieldset>
    <div class="form-group">
     <button type="button" name="add_more" class="btn btn-success" ng-click="addRow()"><span class="glyphicon glyphicon-plus"></span> Add</button>
     <input type="submit" name="submit" class="btn btn-info" value="Save" />
    </div>
   </form>

   <div class="table-responsive">
    <table class="table table-bordered table-striped">
     <tr>
      <th>Name</th>
      <th>Programming Languages</th>
     </tr>
     <tr ng-repeat="name in namesData">
      <td>{{name.name}}</td>
      <td>{{name.programming_languages}}</td>
     </tr>
    </table>
   </div>
  </div>
 </body>
</html>

<script>

var app = angular.module('dynamicApp', []);

app.controller('dynamicController', function($scope, $http){

 $scope.success = false;
 $scope.error = false;

 $scope.fetchData = function(){
  $http.get('fetch_data.php').success(function(data){
   $scope.namesData = data;
  });
 };

 $scope.rows = [{name: 'programming_languages[]', name: 'remove'}];

 $scope.addRow = function(){
  var id = $scope.rows.length + 1;
  $scope.rows.push({'id':'dynamic'+id});
 };

 $scope.removeRow = function(row){
  var index = $scope.rows.indexOf(row);
  $scope.rows.splice(index, 1);
 };

 $scope.formData = {};

 $scope.submitForm = function(){
  $http({
   method:"POST",
   url:"insert.php",
   data:$scope.formData
  }).success(function(data){
   if(data.error != '')
   {
    $scope.success = false;
    $scope.error = true;
    $scope.errorMessage = data.error;
   }
   else
   {
    $scope.success = true;
    $scope.error = false;
    $scope.successMessage = data.message;
    $scope.formData = {};
    $scope.rows = [{name: 'programming_languages[]', name: 'remove'}];
    $scope.fetchData();
   }
  });
 };

});

</script>


fetch_data.php


After this we have make this file and it will fetch data from mysql database and send to angular javascript function.


<?php

//fetch_data.php

include('database_connection.php');

$query = "SELECT * FROM tbl_name ORDER BY id";

$statement = $connect->prepare($query);

if($statement->execute())
{
 while($row = $statement->fetch(PDO::FETCH_ASSOC))
 {
  $data[] = $row;
 }

 echo json_encode($data);
}

?>


insert.php


This last file of this tutorial and under this file we have write PHP code for save or insert data into mysql database by using PHP with AngularJS.


<?php

//insert.php

include('database_connection.php');

$form_data = json_decode(file_get_contents("php://input"));

$error = '';
$message = '';
$validation_error = '';
$name = '';
$programming_languages = '';

if(empty($form_data->person_name))
{
 $error[] = 'Name is Required';
}
else
{
 $name = $form_data->person_name;
}

if(empty($form_data->skill))
{
 $error[] = 'Programming Language is Required';
}
else
{
 foreach($form_data->skill as $language)
 {
  $programming_languages .= $language . ', ';
 }
 $programming_languages = substr($programming_languages, 0, -2);
}

$data = array(
 ':name'      => $name,
 ':programming_languages' => $programming_languages
);

if(empty($error))
{
 $query = "
 INSERT INTO tbl_name 
 (name, programming_languages) VALUES 
 (:name, :programming_languages)
 ";
 $statement = $connect->prepare($query);
 if($statement->execute($data))
 {
  $message = 'Data Inserted';
 }
}
else
{
 $validation_error = implode(", ", $error);
}

$output = array(
 'error'  => $validation_error,
 'message' => $message
);

echo json_encode($output);

?>

So, this is complete source code of Add or Remove input fields dynamically in AngularJS with PHP. If you want to get complete file of this tutorial then you can download by click on below link.




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;