Tuesday, 25 December 2018

Javascript part of the code is not posted to the database

I am trying to enter data to my database with dynamic textboxes. The dynamic textboxes are created with Javascript. When I try to send the data to my database I see that my PHP script is posting only the first row into the database

<div id="form">
  <form name="reaction" id="reaction" method="post" action="./post.php">
  //The first row is created in HTML
  <input type="text" name="firstname[]" id="firstname1" placeholder="Firstname" /> <br />
</div>

//The other rows are created in Javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>

  $(document).ready(function(){
    var final_total_amt = $('#final_total_amt').text();
    var count = 1;

  $(document).on('click', '#add_row', function(){
    count++;
    $('#total_item').val(count);
    var html_code = '';
    html_code += '<input type="text" placeholder="Firstname'+count+'" name="firstname[]" id="firstname'+count+'" data-srno="'+count+'" /><br />';
  });

  $('#form').append(html_code);
</script>

<button type="submit" class="btn btn-primary" name="send">Save</button>
</form>

In the PHP script I am trying to post the multiple textboxes with:

foreach($_POST['firstname'] as $i => $item) {
  $db3 = new PDO('mysql:host=localhost;dbname=db', 'root', 'pass');
  $query3= "INSERT INTO scu_db(firstname) VALUES (:firstname)";
  $stmt3 = $db3->prepare($query3);
  $exec3 = $stmt3->execute(array(
    ':firstname'     =>  $_POST["firstname"][$i]
  ));
}

The script only posts the first row that is created in HTML to my database.

Does someone know how I can solve this?

Result of var_dump on $_POST['firstname']:

array(1) { [0]=> string(2) "1" }



from Javascript part of the code is not posted to the database

No comments:

Post a Comment