Dynamically Add Remove input fields in PHP with jQuery Ajax

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.

How to add Remove Input fields

I will 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.

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 PRIMARY KEY AUTO_INCREAMENT,
  `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');

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();
	}

?>

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

Dynamically Add Remove input fields in PHP with jQuery Ajax

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 or problems about this tutorial, please comment on the form below.😊

Dynamically Add Remove input fields in PHP with jQuery Ajax

2 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *