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.


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

/// Check SQL connection
if ($conn->connect_error) {

echo"my error";



// 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";


   else if ($result->num_rows > 0) {

   while($row = $result->fetch_assoc()) {


<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>

</div> <!-- Column 3 END -->';



<script src=""></script>

AJAX script

        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
        // Alerts the results to this Div



$(‘.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.

User contributions licensed under: CC BY-SA
9 People found this is helpful