PHP - Add/Remove Multiple Input Fields Dynamically with Jquery Ajax Example Tutorial

May 06, 2024 | PHP jQuery MySql Bootstrap Ajax Laravel 11 Laravel


Hello Dev,

In this tutorial, we'll explore how to dynamically add and remove form input fields using jQuery and then save them into a database using PHP. We'll cover handling dynamically added fields and saving their values in a MySQL database using PHP Bootstrap. I'll provide a comprehensive example of adding/removing input fields dynamically and submitting them to the database using jQuery AJAX and PHP. This functionality is crucial when clients need to insert multiple values into a database simultaneously. Providing an input box with a "+" button allows users to add multiple values conveniently. Follow these steps to proceed.

To dynamically add and remove form input fields using jQuery and store them in a MySQL database using PHP, follow these steps:

Step 1: Create the Database Table

First, create a database named test and a table named tagslist with two columns: id and name. You can use the following SQL query to create the table:

Read Also: Laravel 11 CRUD Application Tutorial Example
CREATE TABLE IF NOT EXISTS `tagslist` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci AUTO_INCREMENT=24 ;
Step 2: Create the HTML Form with jQuery

Create an index.php file with the following HTML and jQuery code. This code includes a form with an input field and a button to add more fields. It also includes a submit button to send the form data to the server.

index.php
<!DOCTYPE html>
<html>
<head>
    <title>PHP - Add/Remove Multiple Input Fields Dynamically with Jquery Ajax Example Tutorial -- ItErrorSolution.com</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>
    <div class="container">
        <h2>PHP - Add/Remove Multiple Input Fields Dynamically with Jquery Ajax Example Tutorial -- ItErrorSolution.com</h2>
        <form name="add_name" id="add_name">
            <div class="table-responsive">
                <table class="table table-bordered" id="dynamic_field">
                    <tr>
                        <td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
                        <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
                    </tr>
                </table>
                <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
            </div>
        </form>
    </div>

    <script>
        $(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><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').click(function(){
                $.ajax({
                    url:"name.php",
                    method:"POST",
                    data:$('#add_name').serialize(),
                    success:function(data){
                        alert(data);
                        $('#add_name')[0].reset();
                    }
                });
            });
        });
    </script>
</body>
</html>
Step 3: Process the Form Data with PHP

Create a name.php file to process the form data sent via AJAX. This file will insert the data into the tagslist table in the test database.

Read Also: Laravel Image Gallery Tutorial Using Bootstrap Example name.php
<?php
// Database connection
$host = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbname = "test";

// Create connection
$conn = new mysqli($host, $dbUsername, $dbPassword, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: ". $conn->connect_error);
}

// Get form data
$name = $_POST['name'];

// Prepare and bind
$stmt = $conn->prepare("INSERT INTO tagslist (name) VALUES (?)");
$stmt->bind_param("s", $name);

// Execute statement
$stmt->execute();

// Close statement and connection
$stmt->close();
$conn->close();

echo "New record created successfully";
?>

This setup allows users to dynamically add and remove input fields using jQuery and submit the data to a MySQL database using PHP. The "+" button functionality is achieved by appending new rows to the table with input fields, and the "X" button removes the row. The form data is submitted via AJAX to the server, where it is processed and stored in the database.

Output PHP - Add/Remove Multiple Input Fields Dynamically with Jquery Ajax Example Tutorial

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#PHP
#jQuery
#MySql
#Bootstrap
#Ajax
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"