Wednesday, 14 March 2018

Ajax Crud on Dynamically Add Remove Input Fields in PHP



This tutorial cover topic on Ajax Crud Operation on Dynamic Generated HTML Input field by using Jquery with PHP Script. Here we will discuss how can we insert or add, update or edit dynamically generated html input fields form data in PHP with Mysql using Ajax Jquery. There are many event occurs when we want to insert or edit multiple data of same fields in HTML form which user has filled up details. So, at that time we want to generate dynamic html input fields, so user can enter multiple data of same fields. This type of feature we have discuss here.
First we want to Fetch data from Mysql table and display on web page, so for this we have make one jquery function with ajax request. This function will send Ajax request to PHP script for fetch data from mysql table and display on web page in define division tag with id attribute is result.






<!--index.php !-->

<html>
 <head>
  <title>Ajax Crud on Dynamically Add Remove Input Fields in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.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.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <br />
   <h2 align="center">Ajax Crud on Dynamically Add Remove Input Fields in PHP</h2><br />
   <div align="right">
    
   </div>
   <br />
   <div id="result"></div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 load_data();

 function load_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('#result').html(data);
   }
  })
 }

</script>



<?php

//fetch.php

include('database_connection.php');

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

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

$statement->execute();

$result = $statement->fetchAll();

$total_rows = $statement->rowCount();

$output = '
<div class="table-responsive">
 <table class="table table-bordered table-striped">
  <tr>
   <th>Name</th>
   <th>Programming Languages</th>
   <th>Edit</th>
   <th>Delete</th>
  </tr>
';

if($total_rows > 0)
{
 foreach($result as $row)
 {
  $output .= '
  <tr>
   <td>'.$row["name"].'</td>
   <td>'.$row["programming_languages"].'</td>
   <td><button type="button" name="edit" id="'.$row["id"].'" class="btn btn-warning btn-xs edit">Edit</button></td>
   <td><button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button></td>
  </tr>
  ';
 }
}
else
{
 $output .= '
 <tr>
  <td colspan="4">No Data Found</td>
 </tr>
 ';
}
$output .= '</table></div>';

echo $output;

?>


The above code will display Mysql table data on web page when page has been load into browser. After this we want to insert dynamically generated html input fields data into Mysql table, so for this first we have make Bootstrap modal. In this modal we have make html form in which user can enter his name and multiple programming language details. For generate dynamic html input fields we have make one jquery function that function will append dynamic html fields into form. When we have submit form data, then it will send Ajax request to PHP server script. So, here we have use Ajax for insert or add dynamic generated html input fields data by using PHP.


<!--index.php !-->

<html>
 <head>
  <title>Ajax Crud on Dynamically Add Remove Input Fields in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.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.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <br />
   <h2 align="center">Ajax Crud on Dynamically Add Remove Input Fields in PHP</h2><br />
   <div align="right">
    <button type="button" name="add" id="add" class="btn btn-info">Add</button>
   </div>
   <br />
   <div id="result"></div>
  </div>
 </body>
</html>

<div id="dynamic_field_modal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="add_name">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal">&times;</button>
     <h4 class="modal-title">Add Details</h4>
    </div>
    <div class="modal-body">
     <div class="form-group">
           <input type="text" name="name" id="name" class="form-control" placeholder="Enter your name" />
          </div>
          <div class="table-responsive">
           <table class="table" id="dynamic_field">

           </table>
          </div>
    </div>
    <div class="modal-footer">
     <input type="hidden" name="hidden_id" id="hidden_id" />
     <input type="hidden" name="action" id="action" value="insert" />
     <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
    </div>
   </form>
  </div>
 </div>

</div>


<script>
$(document).ready(function(){

 load_data();

 var count = 1;

 function load_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('#result').html(data);
   }
  })
 }

 function add_dynamic_input_field(count)
 {
  var button = '';
  if(count > 1)
  {
   button = '<button type="button" name="remove" id="'+count+'" class="btn btn-danger btn-xs remove">x</button>';
  }
  else
  {
   button = '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
  }
  output = '<tr id="row'+count+'">';
  output += '<td><input type="text" name="programming_languages[]" placeholder="Add Programming Languages" class="form-control name_list" /></td>';
  output += '<td align="center">'+button+'</td></tr>';
  $('#dynamic_field').append(output);
 }

 $('#add').click(function(){
  $('#dynamic_field').html('');
  add_dynamic_input_field(1);
  $('.modal-title').text('Add Details');
  $('#action').val("insert");
  $('#submit').val('Submit');
  $('#add_name')[0].reset();
  $('#dynamic_field_modal').modal('show');
 });

 $(document).on('click', '#add_more', function(){
  count = count + 1;
  add_dynamic_input_field(count);
 });

 $(document).on('click', '.remove', function(){
  var row_id = $(this).attr("id");
  $('#row'+row_id).remove();
 });

 $('#add_name').on('submit', function(event){
  event.preventDefault();
  if($('#name').val() == '')
  {
   alert("Enter Your Name");
   return false;
  }
  var total_languages = 0;
  $('.name_list').each(function(){
   if($(this).val() != '')
   {
    total_languages = total_languages + 1;
   }
  });

  if(total_languages > 0)
  {
   var form_data = $(this).serialize();

   var action = $('#action').val();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(action == 'insert')
     {
      alert("Data Inserted");
     }
     if(action == 'edit')
     {
      alert("Data Edited");
     }
     add_dynamic_input_field(1);
     load_data();
     $('#add_name')[0].reset();
     $('#dynamic_field_modal').modal('hide');
    }
   });
  }
  else
  {
   alert("Please Enter at least one programming languages");
  }
 });
</script>



<?php

//action.php

include('database_connection.php');

if(isset($_POST["action"]))
{
 $programming_languages = implode(",", $_POST["programming_languages"]);
 $data = array(
  ':name'      => $_POST["name"],
  ':programming_languages' => $programming_languages
 );
 $query = '';
 if($_POST["action"] == "insert")
 {
  $query = "INSERT INTO tbl_name (name, programming_languages) VALUES (:name, :programming_languages)";
 }
 
 $statement = $connect->prepare($query);
 $statement->execute($data);
}


?>






The above code will insert or add dynamic generated html input fields data by using PHP. In this code you can also find jquery code for generate dynamic input fields and how to remove dynamic input fields jquery code also.
After this we want to edit or update details of dynamically generated html input fields. For this also first we want to fetch particular data details. For this also we have use Ajax request. That request will fetch particular data details and display that data under it's respective form fields. Then after when we have submit form data at that time also here it use ajax request which send to that url for which we have use for insert data. But when we have click on edit button then after when we have submit form data then at that time it will edit details and when we have click on add button and submit form data then at that time it will insert data by using Ajax with PHP and Mysql.



<!--index.php !-->

<html>
 <head>
  <title>Ajax Crud on Dynamically Add Remove Input Fields in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.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.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <br />
   <h2 align="center">Ajax Crud on Dynamically Add Remove Input Fields in PHP</h2><br />
   <div align="right">
    <button type="button" name="add" id="add" class="btn btn-info">Add</button>
   </div>
   <br />
   <div id="result"></div>
  </div>
 </body>
</html>

<div id="dynamic_field_modal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="add_name">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal">&times;</button>
     <h4 class="modal-title">Add Details</h4>
    </div>
    <div class="modal-body">
     <div class="form-group">
           <input type="text" name="name" id="name" class="form-control" placeholder="Enter your name" />
          </div>
          <div class="table-responsive">
           <table class="table" id="dynamic_field">

           </table>
          </div>
    </div>
    <div class="modal-footer">
     <input type="hidden" name="hidden_id" id="hidden_id" />
     <input type="hidden" name="action" id="action" value="insert" />
     <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
    </div>
   </form>
  </div>
 </div>

</div>


<script>
$(document).ready(function(){

 load_data();

 var count = 1;

 function load_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('#result').html(data);
   }
  })
 }

 function add_dynamic_input_field(count)
 {
  var button = '';
  if(count > 1)
  {
   button = '<button type="button" name="remove" id="'+count+'" class="btn btn-danger btn-xs remove">x</button>';
  }
  else
  {
   button = '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
  }
  output = '<tr id="row'+count+'">';
  output += '<td><input type="text" name="programming_languages[]" placeholder="Add Programming Languages" class="form-control name_list" /></td>';
  output += '<td align="center">'+button+'</td></tr>';
  $('#dynamic_field').append(output);
 }

 $('#add').click(function(){
  $('#dynamic_field').html('');
  add_dynamic_input_field(1);
  $('.modal-title').text('Add Details');
  $('#action').val("insert");
  $('#submit').val('Submit');
  $('#add_name')[0].reset();
  $('#dynamic_field_modal').modal('show');
 });

 $(document).on('click', '#add_more', function(){
  count = count + 1;
  add_dynamic_input_field(count);
 });

 $(document).on('click', '.remove', function(){
  var row_id = $(this).attr("id");
  $('#row'+row_id).remove();
 });

 $('#add_name').on('submit', function(event){
  event.preventDefault();
  if($('#name').val() == '')
  {
   alert("Enter Your Name");
   return false;
  }
  var total_languages = 0;
  $('.name_list').each(function(){
   if($(this).val() != '')
   {
    total_languages = total_languages + 1;
   }
  });

  if(total_languages > 0)
  {
   var form_data = $(this).serialize();

   var action = $('#action').val();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(action == 'insert')
     {
      alert("Data Inserted");
     }
     if(action == 'edit')
     {
      alert("Data Edited");
     }
     add_dynamic_input_field(1);
     load_data();
     $('#add_name')[0].reset();
     $('#dynamic_field_modal').modal('hide');
    }
   });
  }
  else
  {
   alert("Please Enter at least one programming languages");
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr("id");
  $.ajax({
   url:"select.php",
   method:"POST",
   data:{id:id},
   dataType:"JSON",
   success:function(data)
   {
    $('#name').val(data.name);
    $('#dynamic_field').html(data.programming_languages);
    $('#action').val('edit');
    $('.modal-title').text("Edit Details");
    $('#submit').val("Edit");
    $('#hidden_id').val(id);
    $('#dynamic_field_modal').modal('show');
   }
  });
 });

</script>



<?php

//select.php

include('database_connection.php');

if(isset($_POST["id"]))
{
 $query = "SELECT * FROM tbl_name WHERE id='".$_POST["id"]."'";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 $programming_languages = '';
 $name = '';
 foreach($result as $row)
 {
  $name = $row["name"];
  $language_array = explode(",", $row["programming_languages"]);
  $count = 1;
  foreach($language_array as $language)
  {
   $button = '';
   if($count > 1)
   {
    $button = '<button type="button" name="remove" id="'.$count.'" class="btn btn-danger btn-xs remove">x</button>';
   }
   else
   {
    $button = '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
   }
   $programming_languages .= '
    <tr id="row'.$count.'">
     <td><input type="text" name="programming_languages[]" placeholder="Add Programming Languages" class="form-control name_list" value="'.$language.'" /></td>
     <td align="center">'.$button.'</td>
    </tr>
   ';
   $count++;
  }
 }
 $output = array(
  'name'     => $name,
  'programming_languages' => $programming_languages
 );
 echo json_encode($output);
}


?>



<?php

//action.php

include('database_connection.php');

if(isset($_POST["action"]))
{
 $programming_languages = implode(",", $_POST["programming_languages"]);
 $data = array(
  ':name'      => $_POST["name"],
  ':programming_languages' => $programming_languages
 );
 $query = '';
 if($_POST["action"] == "insert")
 {
  $query = "INSERT INTO tbl_name (name, programming_languages) VALUES (:name, :programming_languages)";
 }
 if($_POST["action"] == "edit")
 {
  $query = "
  UPDATE tbl_name 
  SET name = :name, 
  programming_languages = :programming_languages 
  WHERE id = '".$_POST['hidden_id']."'
  ";
 }

 $statement = $connect->prepare($query);
 $statement->execute($data);
}


?>

Above source code will fetch particular data from select.php and display under bootstrap modal form and when user has submit form then form data will be edited. If user want to to add more data or remove data then also he can do this type of things.
Lastly, we want to delete or remove data by using Ajax with PHP. So, for also we have make jquery code with Ajax request, so when we have click on delete button then jquery code will fire with Ajax request which send to PHP script and that script with delete or remove data from Mysql table after this remaining data will be display on web page without refresh of web page.



<!--index.php !-->

<html>
 <head>
  <title>Ajax Crud on Dynamically Add Remove Input Fields in PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.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.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">
   <br />
   <br />
   <h2 align="center">Ajax Crud on Dynamically Add Remove Input Fields in PHP</h2><br />
   <div align="right">
    <button type="button" name="add" id="add" class="btn btn-info">Add</button>
   </div>
   <br />
   <div id="result"></div>
  </div>
 </body>
</html>

<div id="dynamic_field_modal" class="modal fade" role="dialog">
 <div class="modal-dialog">
  <div class="modal-content">
   <form method="post" id="add_name">
    <div class="modal-header">
     <button type="button" class="close" data-dismiss="modal">&times;</button>
     <h4 class="modal-title">Add Details</h4>
    </div>
    <div class="modal-body">
     <div class="form-group">
           <input type="text" name="name" id="name" class="form-control" placeholder="Enter your name" />
          </div>
          <div class="table-responsive">
           <table class="table" id="dynamic_field">

           </table>
          </div>
    </div>
    <div class="modal-footer">
     <input type="hidden" name="hidden_id" id="hidden_id" />
     <input type="hidden" name="action" id="action" value="insert" />
     <input type="submit" name="submit" id="submit" class="btn btn-info" value="Submit" />
    </div>
   </form>
  </div>
 </div>

</div>


<script>
$(document).ready(function(){

 load_data();

 var count = 1;

 function load_data()
 {
  $.ajax({
   url:"fetch.php",
   method:"POST",
   success:function(data)
   {
    $('#result').html(data);
   }
  })
 }

 function add_dynamic_input_field(count)
 {
  var button = '';
  if(count > 1)
  {
   button = '<button type="button" name="remove" id="'+count+'" class="btn btn-danger btn-xs remove">x</button>';
  }
  else
  {
   button = '<button type="button" name="add_more" id="add_more" class="btn btn-success btn-xs">+</button>';
  }
  output = '<tr id="row'+count+'">';
  output += '<td><input type="text" name="programming_languages[]" placeholder="Add Programming Languages" class="form-control name_list" /></td>';
  output += '<td align="center">'+button+'</td></tr>';
  $('#dynamic_field').append(output);
 }

 $('#add').click(function(){
  $('#dynamic_field').html('');
  add_dynamic_input_field(1);
  $('.modal-title').text('Add Details');
  $('#action').val("insert");
  $('#submit').val('Submit');
  $('#add_name')[0].reset();
  $('#dynamic_field_modal').modal('show');
 });

 $(document).on('click', '#add_more', function(){
  count = count + 1;
  add_dynamic_input_field(count);
 });

 $(document).on('click', '.remove', function(){
  var row_id = $(this).attr("id");
  $('#row'+row_id).remove();
 });

 $('#add_name').on('submit', function(event){
  event.preventDefault();
  if($('#name').val() == '')
  {
   alert("Enter Your Name");
   return false;
  }
  var total_languages = 0;
  $('.name_list').each(function(){
   if($(this).val() != '')
   {
    total_languages = total_languages + 1;
   }
  });

  if(total_languages > 0)
  {
   var form_data = $(this).serialize();

   var action = $('#action').val();
   $.ajax({
    url:"action.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(action == 'insert')
     {
      alert("Data Inserted");
     }
     if(action == 'edit')
     {
      alert("Data Edited");
     }
     add_dynamic_input_field(1);
     load_data();
     $('#add_name')[0].reset();
     $('#dynamic_field_modal').modal('hide');
    }
   });
  }
  else
  {
   alert("Please Enter at least one programming languages");
  }
 });

 $(document).on('click', '.edit', function(){
  var id = $(this).attr("id");
  $.ajax({
   url:"select.php",
   method:"POST",
   data:{id:id},
   dataType:"JSON",
   success:function(data)
   {
    $('#name').val(data.name);
    $('#dynamic_field').html(data.programming_languages);
    $('#action').val('edit');
    $('.modal-title').text("Edit Details");
    $('#submit').val("Edit");
    $('#hidden_id').val(id);
    $('#dynamic_field_modal').modal('show');
   }
  });
 });

 $(document).on('click', '.delete', function(){
  var id = $(this).attr("id");
  if(confirm("Are you sure want to remove this data?"))
  {
   $.ajax({
    url:"delete.php",
    method:"POST",
    data:{id:id},
    success:function(data)
    {
     load_data();
     alert("Data removed");
    }
   })
  }
 });

});
</script>



<?php

//delete.php

include('database_connection.php');

if(isset($_POST["id"]))
{
 $query = "DELETE FROM tbl_name WHERE id = '".$_POST['id']."'";
 $statement = $connect->prepare($query);
 $statement->execute();
}


?>


So, this complete source code of how to do crud operation like insert, update, delete data on dynamically generated html input fields by using Ajax Jquery with PHP & Mysql. If you want complete source code then by clicking on below link you can find complete source code of this tutorial.




0 comments:

Post a Comment