Reputation: 1909
Is there a way to loop through elements and pass the element value in the data: {} option of $.ajax()?
eg.
$res = pg_query($con, "select * from tbl_salary_deductions");
while($row = pg_fetch_assoc($res)) {
echo "<input type=checkbox class='dlccat' id='" . $row['dlcid']. "'> Category " . $row['dlccategory'] . "<br>";
}
creates the checkboxes. Then in the call pass only the checked ones so I can process them server side:
$.ajax({
url: 'ajax/register_driver.php',
data: {
//dlccat
$.each($(".dlccat:checked"), function() {
dlcat + $(this).id: true,
});
},
success: function () {
},
error: function () {
alert('DATA UPDATE FAILED. PLEASE TRY AGAIN!');
}
})
Need to save in the db the values of the checked items as per pic.
Upvotes: 0
Views: 1711
Reputation: 1277
$.ajax() is the implementation of XMLHttpRequest that is exposed by jQuery. Consider it to be a function call to which you are passing initialisation parameters like url, data, dataType etc. The "data" option that you pass to $.ajax should be an object. It wouldn't be evaluated/run as a function as you are expecting in your case.
The above code would give a syntax error because you are trying to evaluate a loop (the each statement) inside an object.
The correct way would be to first form an object using the each statement and then pass that object to the $.ajax method.
Would be something like this.
var obj = {};
$(".dlccat:checked").each(function() {
obj["dlcat_" + this.id] = true;
});
//to add other params, extend this object
$.extend(obj, {"otherParam" : "otherParamsValue"});
Then in $.ajax, pass this obj variable as data. They would be received as GET params
$.ajax({
url: 'ajax/register_driver.php',
data: obj,
success: function () {
},
error: function () {
alert('DATA UPDATE FAILED. PLEASE TRY AGAIN!');
}
})
Upvotes: 2