In this article, you can read more about how to add remove input fields dynamically in PHP with Jquery Ajax. if you want to add or remove input fields dynamically then you can see the following example.
sometimes we need to add bulk data. eg. education data. so here we are taking one input box and explaining you through a simple example.
<html lang="en"> <head> <title>Add Remove Input Fields Dynamically in PHP with Jquery Ajax - XpertPhp</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <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:"data.php", method:"POST", data:$('#add_name').serialize(), success:function(data) { alert(data); $('#add_name')[0].reset(); } }); }); }); </script> </head> <body> <div class="container"> <div class="form-group"> <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> </div> </body> </html>
data.php
<?php $connect = mysqli_connect("localhost", "root", "", "test"); $number = count($_POST["name"]); if($number > 0) { for($i=0; $i<$number; $i++) { if(trim($_POST["name"][$i] != '')) { $sql = "INSERT INTO student VALUES('".mysqli_real_escape_string($connect, $_POST["name"][$i])."')"; mysqli_query($connect, $sql); } } echo "Data Inserted"; } else { echo "Please Enter Name"; } ?>
Please follow and like us: