AdSense

Dynamically Add / Remove input fields in PHP with Jquery Ajax, PHP - Dynamically Add Remove input fields using JQuery Ajax Example with Demo, 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. system, software


This post will show you how to add and remove (Repeater) form input fields dynamically using jQuery and store in a database users table using PHP. Here's how to use PHP Bootstrap to handle dynamically added fields stored in a MySQL database. I'll show you a complete example of dynamically adding / removing inputs and passing fields to the database using jquery ajax and PHP. User can enter multiple information at the same time. User can add group data at the same time.

We have to add almost more functions if the client wants to enter multiple values ​​into the database at the same time. It's great when you use something interesting by giving them an input field with a "+" button so they can add multiple values ​​at once.

Here you only need to take a few steps to proceed.


  1. Create Database and Table
  2. Create Database connection with MySQL
  3. Create HTML File index page, jQuery & AJAX
  4. Create PHP code file

Step 1:  Create Database and Table

In the first step we need to create a database and tables, so here I have created a database of tables "Testing" and "Users" with identifiers and columns with names. You simply create a Users table as described in the SQL query.



SQL Query:

--
-- Database: `testing`

-- Table structure for table `users`
--

CREATE TABLE `users` (
  `id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `users`
--

INSERT INTO `users` (`id`, `name`, `email`) VALUES
(1, 'undertaker', 'undertaker23@gmail.com'),
(2, 'john cena', 'john12@gmail.com'),
(3, 'kane', 'kane51@gmail.com'),
(4, 'roman', 'roman65@gmail.com'),
(5, 'seth', 'seth56@gmail.com');


Step 2 : Create Database connection with MySQL

<?php
	// Database configuration 
	$hostname = "localhost"; 
	$username = "root"; 
	$password = ""; 
	$dbname   = "testing"; 
	 
	// Create database connection 
	$conn = mysqli_connect($hostname, $username, $password, $dbname); 
	 
	// Check connection
	if(mysqli_connect_errno()) {
	  echo "Failed to connect to MySQL: " . mysqli_connect_error();
	  exit();
	}

?>

Step 3 : Create HTML File index page,  jQuery & AJAX

Here we need to create an index.php file and I created a form with fields for entering name, email and a button. I also wrote code to add more fields to jquery. So let's create an index.php file and paste in the following code.

index.php
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Dynamic add/remove input fields in PHP Jquery AJAX</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>

<div class="card text-center" style="margin-bottom:50px;">
  <h1>Dynamic Add/Remove input fields in PHP Jquery AJAX</h1>
</div>
  
<div class="container">
  <div class="row">
    <div class="col-md-1"></div>
      <div class="col-md-10">
        <div class="form-group">
          <form name="add_name" id="add_name">
            <table class="table table-bordered table-hover" id="dynamic_field">
              <tr>
                <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
                <td><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></td>
                <td><button type="button" name="add" id="add" class="btn btn-primary">Add More</button></td>  
              </tr>
            </table>
            <input type="submit" class="btn btn-success" name="submit" id="submit" value="Submit">
          </form>
        </div>
      </div>
    <div class="col-md-1"></div>
  </div>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>

<script type="text/javascript">
  $(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><input type="text" name="email[]" placeholder="Enter your Email" class="form-control name_email"/></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").on('click',function(){
      var formdata = $("#add_name").serialize();
      $.ajax({
        url   :"action.php",
        type  :"POST",
        data  :formdata,
        cache :false,
        success:function(result){
          alert(result);
          $("#add_name")[0].reset();
        }
      });
    });
  });
</script>



Output

Dynamic Add/Remove input fields in PHP Jquery AJAX, Dynamically Add / Remove input fields in PHP with Jquery Ajax,PHP - Dynamically Add Remove input



Step 4 : Create PHP code file

In this step, we will write code for insert data into database users table using Mysql query. So, we have to create a action.php file and put bellow code

action.php
<?php

	include_once('config.php');

	$userData = count($_POST["name"]);
	
	if ($userData > 0) {
	    for ($i=0; $i < $userData; $i++) { 
		if (trim($_POST['name'] != '') && trim($_POST['email'] != '')) {
			$name   = $_POST["name"][$i];
			$email  = $_POST["email"][$i];
			$query  = "INSERT INTO users (name,email) VALUES ('$name','$email')";
			$result = mysqli_query($con, $query);
		}
	    }
	    echo "Data inserted successfully";
	}else{
	    echo "Please Enter user name";
	}

?>



You can always support by sharing on social media or recommending my blog to your friends and colleagues.   
If you have any suggestions / problems about this tutorial, please comment on the  form below.😊

Post a Comment

Previous Post Next Post