Ryan D Ryan D - 1 year ago 96
jQuery Question

Ajax form submit wont post form field value from while loop

I am trying to submit a form which is being displayed with images from my db in a while loop. Im using ajax so it will not refresh the page and loose my place, I have a form that updates the datetime in the db when submitted but when the form submits it only shows the most recent id from the while loop..

Here is the getFeed.php

//Display feed with form
$sql = "SELECT * FROM images ORDER BY id desc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '<div id="mainCont">';
while($row = $result->fetch_assoc()) {
$path = $row['path'];
$user = $row['user'];
$id = $row['id'];

echo '<img id="pic" src="/mobile/uploads/'.$path.'"/>';
echo '<div id="userCont">';
echo '<div id="user">@'.$user.'</div>';
echo '<div id="com"><img src="../img/com.png"/>0</div>';
echo '<form method="post" data-ajax="false">';
echo '<input name="id" data-ajax="false" id="id" type="text" value="'.$id.'" />';
echo '<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm();" value="Send" />';
echo ' </form>';


echo '</div>';
}
echo '</div>';


Here is the ajax call in index.php

<script type="text/javascript">
//Calling Feed
repeatAjax();
function repeatAjax(){
$.ajax({
type: "GET",
url: "getFeed.php",
dataType: "html",
success: function(response){
$("#response").html(response);

},
});
};

//Submit Form
function SubmitForm() {
event.preventDefault();
var name = $('#id').val();
console.log(name);
$.post("bump.php", {name: name},
function(data) {

});
}
</script>


I have 3 post in the database that have id's of 100,101,102. when the form is submitted log only displays 102 no matter which post form was submitted..

Answer Source

You can use

echo '<input name="id" data-ajax="false" id="field_'.$id.'" type="text" value="'.$id.'" />';
echo '<input type="image" style="height:35px;top:4px;" id="bump" src="../img/bump.png" id="searchForm" onclick="SubmitForm('.$id.');" value="Send" />';

and for submission

//Submit Form
function SubmitForm(id) {
    event.preventDefault();
    var name = $('#field_'+id).val();
    console.log(name);
    // your code
}