I have a form inside a while loop which I want to use to update the database using ajax. The problem is that when I am using ID only the 1st data or 1st row data of the form is sent no matter which button I click. When I change the IDs to CLASSES the console shows undefined.
Error in Console when using classes:
Object { credits: undefined, price: undefined, packId: undefined, type: "savePackage" }
HTML Form:
<div class="content">
<div class="content table-responsive table-full-width">
<table class="table table-hover table-striped">
<tr>
<th>Credits</th>
<th>Price</th>
<th>Action</th>
</tr>
<?php while($pack = $package->fetch()){ extract($pack); ?>
<tr>
<form method="post" action="">
<input type="hidden" value="<?php echo $cp_id; ?>" class="packId">
<td><input type="text" class="form-control" class="editCredits" value="<?php echo $cp_credits; ?>"></td>
<td><input type="text" class="form-control" class="editPrice" value="<?php echo $cp_price; ?>"></td>
<td>
<input type="submit" value="Save" class="btn btn-fill btn-info savePackage">
<input type="submit" value="Delete" class="btn btn-fill btn-danger deletePackage">
</td>
</form>
</tr>
<?php } ?>
</table>
</div>
</div>
AJAX Code
$(document).ready(function() {
$(".savePackage").click(function() {
var dataString = {
credits: $(this).closest('form').find('.editCredits').val(),
price: $(this).closest('form').find('.editPrice').val(),
packId: $(this).closest('form').find('.packId').val(),
type: 'savePackage'
};
console.log(dataString);
var $submit = $(this).parent().find('.savePackage');
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to add this package?',
buttons: {
confirm: function () {
$.ajax({
type: "POST",
//dataType : "json",
url: "ptc-settings-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$submit.val("Please wait...");
},
success: function(html){
$.alert(html);
$submit.val("Save");
}
});
},
cancel: function(){}
}
});
return false;
});
});
I have used $(this).closest('form').find('.editCredits').val()
method here but there are multiple other forms on the same page too. Therefore, maybe using form element in $(this).closest('form')
could be causing a problem.