How to Add or Remove Input Fields Dynamically with JQuery, Ajax, and PHP

infoslearning

In this JQuery tutorial, we will learn how to add and remove input fields dynamically using JQuery, Ajax, and PHP. New input fields will be added dynamically and removed dynamically with JQuery. Dynamically add input fields and submit them to a database with JQuery and PHP. In this tutorial, we will use a MySQL database called “test_db”.

Step 1,  Create a table called “location_tbl” inside a database.

-- phpMyAdmin SQL Dump
-- version 5.1.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 30, 2022 at 10:31 PM
-- Server version: 10.4.22-MariaDB
-- PHP Version: 8.1.2

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";


/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;

--
-- Database: `test_db`
--

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

--
-- Table structure for table `location_tbl`
--

CREATE TABLE `location_tbl` (
  `id` int(11) NOT NULL,
  `location_name` varchar(20) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

--
-- Dumping data for table `location_tbl`
--

INSERT INTO `location_tbl` (`id`, `location_name`) VALUES
(8, 'Los Angels'),
(9, 'Los Angels');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `location_tbl`
--
ALTER TABLE `location_tbl`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `location_tbl`
--
ALTER TABLE `location_tbl`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

 

Step 2, Create a file called “dbconnection.php” for database connection. Inside ”dbconnection.php” write the following code.

<?php 
// DB credentials.
define('DB_HOST','localhost');
define('DB_USER','root');
define('DB_PASS','');
define('DB_NAME','test_db');
// Establish database connection.
try
{
$dbh = new PDO("mysql:host=".DB_HOST.";dbname=".DB_NAME,DB_USER, DB_PASS,array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch (PDOException $e)
{
	//$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
exit("Error: " . $e->getMessage());
}
?>

Step 3, Create an “index.html” file. Write the following code.

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Dynamic add or remove text field</title>
	<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
 <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
	<div class="container">
		<br/>
		<br/>
<h1 align="center">Dynamic add or remove input field using Jquery, Ajax, PHP</h1>
<div class="form-group">
	<form name="add_location" id="add_location">
		<table class="table table-bordered" id="dynamic_input">
			<tr>
				<td><input type="text" name="location_name[]" id="location_name" class="form-control" placeholder="Enter location"></td>
				<td><button type="submit" name="submit" id="button_id" class="btb btn-success">Add</button></td>

			</tr>
			

		</table>
		<button type="submit" name="submit" class="btn btn-primary" id="submit" />Submit</button>
	</form>

</div>

	</div>

</body>
</html>

<script type="text/javascript">
	
	$(document).ready(function(){
		var i=1;
		$('#button_id').click(function(){
			i++;
			$('#dynamic_input').append('<tr id="row'+i+'"><td><input type="text" name="location_name[]" id="location_name" class="form-control" placeholder="Enter location" required="true"></td><td><button type="button" name="remove" id="'+i+'" class="btb btn-danger btn_remove">Remove</button></td></tr>');
		});
		$(document).on('click','.btn_remove', function(){
			var button_ID=$(this).attr("id");
           $("#row"+button_ID+"").remove();
		});

		//submti data into a database
		$('#submit').click(function(){
			$.ajax({

				url:"post.php",
				method:"POST",
				data:$("#add_location").serialize(),
				success:function(data)
				{
					alert(data);
					$('$add_location')[0].reset();
				}
			});
		});
	});
</script>

Step 4, Create “post.php” for PHP code. Write the following code.

<?php
//include database connection here
include 'dbconnection.php';

//count number of values arrays in, if number less than zero then it display message please add the location name

$number=count($_POST["location_name"]);
if($number >1)
{


	//if number is greater than zero, make loop for fetch all array values
for($i=0; $i<$number; $i++){
	$location_name=$_POST['location_name'][$i];

if(trim($_POST["location_name"][$i]) !=''){

//insert query
$sql1="INSERT INTO location_tbl (location_name) VALUES (:location_name)";
$query1=$dbh->prepare($sql1);
$query1->bindParam(':location_name',$location_name,PDO::PARAM_STR);
 $query1->execute();
 

   $LastInsertId=$dbh->lastInsertId();
      if ($LastInsertId>0) {
      echo '<script>alert("Location added.")</script>';
     echo "<script>window.location.href ='index.html'</script>";

      }

}

}
}
else{
echo "Enter location name";
}
?>

Run localhost project; http://localhost/test/


Other Recommended for you

  • .How to Reload Page Using JavaScript after a certain Time.
  • .What is JSON? | JSON vs XML | JSON Explained