Reputation: 77
I have a PHP for each loop. Inside the foreach loop, I have HTML input elements. Those input values are processed through an ajax and then stored in the DB. The problem is no matter which form I submit. Only the first form will get submitted.
I figure out that the problem is in the submit button. Whenever I submit only the first-row input values are been passed into the ajax. Surprisingly when I wrap my input in form tag and by the values by calling the action directly into the form it works like a champ. But I want to submit the input values without refreshing the webpage. So I have an index to keep the track of the form and pass the index in the submit onlick() function. But don't know how to process that index through ajax to submit the right values.
<?php
$index = 0;
$data = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($data as $row) {
<div>
<input type="hidden" name="id" value="<?php echo $row['no'] ?>"><br>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio" value="NO">NO
<input type="radio" name="optradio" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio1" value="NO">NO
<input type="radio" name="optradio1" value="YES">YES
</div>
</fieldset>
<fieldset>
<div>
<label>XYZ Question</label>
</div>
<div>
<input type="radio" name="optradio2" value="NO">NO
<input type="radio" name="optradio2" value="YES">YES
</div>
</fieldset>
<button onclick="launchAjax('.$index.')" class="btn">SUBMIT</button>
</div>
$index++;
}
?>
My ajax code:
function launchAjax(index){
$.post(
"inbetween.php/",
{
id: $("[name=id]").val(),
question: $("[name=optradio]:checked").val(),
question1: $("[name=optradio1]:checked").val(),
question2: $("[name=optradio2]:checked").val(),
}
);
}
});
Upvotes: 0
Views: 171
Reputation: 781068
The index is unnecessary. If you want to get the values from the current DIV, pass this
as an argument to the function. Then you can use jQuery DOM traversal functions to find the related inputs.
<button type="button" onclick="launchAjax(this)" class="btn">SUBMIT</button>
function launchAjax(element) {
var div = $(element).closest("div");
$.post(
"inbetween.php/", {
id: $("[name=id]", div).val(),
question: $("[name=optradio]:checked", div).val(),
question1: $("[name=optradio1]:checked", div).val(),
question2: $("[name=optradio2]:checked", div).val(),
}
);
}
BTW, using the same names for the radio buttons each time through the loop means that you'll just have one set of radio buttons for all rows returned by the query -- checking an option in one row will uncheck that corresponding option in all the other rows. You need to give them different names in each iteration. For the launchAjax9)
function to work, you could also give them classes, and use that instead of [name=optradio]
; there's no problem with using the same classes in each iteration.
Upvotes: 1