0

The code below display 3 records successfully.

Here is my issue. When I click on submit button to send data to database, only the first form input containing Firstname (Joe) and lastname (Deo) gets posted and inserted into database while the remain 2 records does not submit. How can I ensure that all the three records rows in the form inputs gets submitted?

index.html

<!doctype html>
  <html>
   <head>
<script src="jquery.min.js"></script>

  </head>
  <body> 

 <h1>Send Record</h1>
<div id="record"></div> 
<div id="record_btn"></div>
<script>
var json = [{
    "firstName": "John",
        "lastName": "Doe"
}, {
    "firstName": "Anna",
        "lastName": "Smith"
}, {
    "firstName": "Peter",
        "lastName": "Jones"
}];

$(document).ready(function(){
 var len = json.length;
            for(var i=0; i<len; i++){
              
                var firstname = json[i].firstName;
                var lastname = json[i].lastName;
               

                var tr_str = "<div>" +
                    "<td align='center'>" + (i+1) + "</td>" +

                    "<input type='text' id='firstname' name='firstname' value="+ firstname +">" +
                      "<input type='text' id='lastname' name='lastname' value="+ lastname +">" +  
                      //"<td align='center'><button id='send1' name='send1'>submit individually</button></td>" +
                    "</div>";

                $("#record").append(tr_str);
            }

 $('#record_btn').html("<button id='send2' name='send2'>submit All</button>");

});



// submit form

$(document).ready(function(){
    $('#send2').click(function(){
//$(document).on( 'click', '#send1', function(){ 
//$(document).on( 'click', '#send2', function(){    
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();

alert(firstname);
alert(lastname);


if(firstname ==''){
alert('empty');
}
else{
        
var rec = "firstname="+ firstname + "&lastname=" + lastname;
        
        $.ajax({
            
            type:'POST',
            url:'insert.php',
            data:rec,
            cache:false,
            success:function(data){
    
                            alert('Record Inserted Successfully.');         
            }
            
        });
        
        }   
})

});



</script>

  </body>
</html>

insert.php

<?php


// pdo_connect.php

$st = $db->prepare('INSERT INTO users(firstname,lastname) values (:firstname,:lastname)');
$st->execute(array( 
':firstname' => $_POST["firstname"],
':lastname' => $_POST["lastname"],
));




/*

        foreach ($_POST["firstname"] as $key => $value) {
$st = $db->prepare('INSERT INTO users(firstname,lastname) values (:firstname,:lastname)');
$st->execute(array( 
':firstname' => $_POST["firstname"],
':lastname' => $_POST["lastname"],
));
        }

*/


?>
halfer
  • 19,824
  • 17
  • 99
  • 186
Nancy Moore
  • 2,322
  • 2
  • 21
  • 38
  • Does this answer your question? [How to Submit Multiple Values in a single HTML Form?](https://stackoverflow.com/questions/43267778/how-to-submit-multiple-values-in-a-single-html-form) – Will B. Jul 11 '20 at 03:06
  • Issue is caused by `id='firstname' name='firstname'`, to be valid syntax the `id` must be unique in the DOM. Then you will need to specify the form field names as an array of values `name='firstname[]'` This will cause `$_POST['firstname']` to be an array instead of a string value – Will B. Jul 11 '20 at 03:07

2 Answers2

0

Here is a solution:

First, you will want to use a different identifier for your input fields. id HTML attribute should be unique for each document. I suggest to use class HTML attribute.

Second, you will want to utilize JSON formatted string to send your information to the server. This way you can easily pass an array of names without problems.

Sample Code:

var json = [{
  "firstName": "John",
  "lastName": "Doe"
}, {
  "firstName": "Anna",
  "lastName": "Smith"
}, {
  "firstName": "Peter",
  "lastName": "Jones"
}];

var people = [];
var numberOfPeople = json.length;

for (var i = 0; i < numberOfPeople; i++) {
  people[i] = {};
  people[i].firstName = $(".firstname")[i].value;
  people[i].lastName = $(".lastname")[i].value;
}

var passThisToTheServer = JSON.stringify(people);
console.log(passThisToTheServer);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type="text" class="firstname" name="firstname" value="John">
<input type="text" class="lastname" name="lastname" value="Doe">

<input type="text" class="firstname" name="firstname" value="Anna">
<input type="text" class="lastname" name="lastname" value="Smith">

<input type="text" class="firstname" name="firstname" value="Peter">
<input type="text" class="lastname" name="lastname" value="Jones">

This is what your jQuery AJAX request would look like:

$.ajax({
    
    type:'POST',
    url:'insert.php',
    data:passThisToTheServer,
    cache:false,
    success:function(data){
        alert('Record Inserted Successfully.');         
    }
    
});

On the PHP side (server side), simply use json_decode to access the JSON string coming from the client side as a PHP array. After that it is a matter of refactoring your SQL statement to insert multiple rows (https://www.mysqltutorial.org/mysql-insert-statement.aspx/).

95faf8e76605e973
  • 13,643
  • 3
  • 24
  • 51
0

Why the first pair of firstname and lastname getting inserted into the database?

Because, the name attribute of the firstname and lastname input elements is the same in all the three pairs. You should use unique name for all the elements inside a form.

You can achieve your solution with below JS snippet

const json = [{
"firstName": "John",
"lastName": "Doe"
}, {
"firstName": "Anna",
"lastName": "Smith"
}, {
"firstName": "Peter",
"lastName": "Jones"
}];
$(document).ready(function(){
   const len = json.length;
      for(let i=0; i<len; i++){

        const firstname = json[i].firstName;
        const lastname = json[i].lastName;


        const tr_str = "<div>" +
        "<td align='center'>" + (i + 1) + "</td>" +
        "<input type='text' id='firstname_"+ i +"' name='firstname_"+ i +"' value=" + firstname + ">" +
        "<input type='text' id='lastname_"+ i +"' name='lastname_"+ i +"' value=" + lastname + ">" +
        "</div>";

    $("#record").append(tr_str);
}

$('#record').append("<input id='send2' type='button' value='Submit all' name='send2'>/>");

$('#send2').click(function() {
    const userDetails = $("#userForm").serialize();
    $.ajax({
        type:'POST',
        url:'insert.php',
        data: userDetails,
        cache:false,
        success:function(data){
            alert('Record Inserted Successfully.');
        }
    });
})

});

And read in PHP:

echo $_POST['userDetails']['firstname_0'];
echo $_POST['userDetails']['lastname_0'];
........
Subbu
  • 663
  • 1
  • 9
  • 20