Skip to content

AJAX POST Form Always posts Data from the first record in the list

I found this issue is related to my AJAX posting method. If I post this form using the standard method (action=””) it works fine it polulates my database according to which record I select in the list to post. But when I use the AJAX Post method it will only poplulate the values with the first record on the SQL Results list. I made my input fields visible and all the posted content is unique and as expected. Below is the full code.

<?php
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
/// Check SQL connection
if ($conn->connect_error) {
echo"my error";
die();
}
// Get the the data from the database
$sql = "SELECT * FROM clients WHERE";
$result = $conn->query($sql);
// Check database connection first
if ($conn->query($sql) === FALSE) {
echo"my error";
exit();
}
   else if ($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
echo'
<div class="col-md-3 bid-section">
<form  action="" method="post" > <!-- Favourites -->
<input type="text" class ="name" name="name" value="'.$row["name"].'">
<input type="text" class ="surname" name="surname" value="'.$row["surname"].'">
<input type="text" class ="country" name="country" value="'.$row["country"].'">
<a   class ="favourite-btn" >
<div class="'.$favicon.'"></div>
</a>
</form>
</div> <!-- Column 3 END -->';
  }
}
mysqli_free_result($result);
mysqli_close($conn);
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
AJAX script
$(document).ready(function(){
    $('.favourite-btn').click(function(event){
       event.preventDefault();
        var field1= $('.name').val();
        var field2= $('.surname').val();
        var field3= $('.country').val();
        $.post('mydirectory/add_names_sql.php', {name:field1, surname:field2  , country:field3},
         // Alert Success
         function(data){
        // Alerts the results to this Div
            $('.favourite-btn').html(data);
        });
    });
});
</script>



Answer

$(‘.name’).val()` is the value of the first element with that class. You need to select the element that’s in the same form as the button that was clicked.

        var form = $(this).closest("form");
        var field1= form.find('.name').val();
        var field2= form.find('.surname').val();
        var field3= form.find('.country').val();

You could also get all the form inputs with:

        var formdata = $(this).closest("form").serialize();

And in the callback function, you also need to update the appropriate element.

form.find('.favourite-btn').html(data);