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.
JavaScript
x
90
90
1
<?php
2
3
// Create connection
4
$conn = new mysqli($servername, $username, $password, $dbname);
5
6
/// Check SQL connection
7
if ($conn->connect_error) {
8
9
echo"my error";
10
11
die();
12
13
}
14
15
// Get the the data from the database
16
17
$sql = "SELECT * FROM clients WHERE";
18
$result = $conn->query($sql);
19
20
// Check database connection first
21
if ($conn->query($sql) === FALSE) {
22
23
echo"my error";
24
25
exit();
26
}
27
28
29
else if ($result->num_rows > 0) {
30
31
while($row = $result->fetch_assoc()) {
32
33
34
echo'
35
36
<div class="col-md-3 bid-section">
37
38
39
<form action="" method="post" > <!-- Favourites -->
40
<input type="text" class ="name" name="name" value="'.$row["name"].'">
41
<input type="text" class ="surname" name="surname" value="'.$row["surname"].'">
42
<input type="text" class ="country" name="country" value="'.$row["country"].'">
43
44
<a class ="favourite-btn" >
45
<div class="'.$favicon.'"></div>
46
</a>
47
</form>
48
49
50
</div> <!-- Column 3 END -->';
51
52
53
}
54
}
55
56
mysqli_free_result($result);
57
mysqli_close($conn);
58
59
?>
60
61
62
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
63
64
<script>
65
AJAX script
66
$(document).ready(function(){
67
68
$('.favourite-btn').click(function(event){
69
event.preventDefault();
70
71
var field1= $('.name').val();
72
var field2= $('.surname').val();
73
var field3= $('.country').val();
74
75
76
$.post('mydirectory/add_names_sql.php', {name:field1, surname:field2 , country:field3},
77
78
// Alert Success
79
function(data){
80
81
// Alerts the results to this Div
82
$('.favourite-btn').html(data);
83
84
});
85
});
86
});
87
</script>
88
•
89
90
Advertisement
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.
JavaScript
1
5
1
var form = $(this).closest("form");
2
var field1= form.find('.name').val();
3
var field2= form.find('.surname').val();
4
var field3= form.find('.country').val();
5
You could also get all the form inputs with:
JavaScript
1
2
1
var formdata = $(this).closest("form").serialize();
2
And in the callback function, you also need to update the appropriate element.
JavaScript
1
2
1
form.find('.favourite-btn').html(data);
2