I want to retrieve id's from selected checkboxes and send them via an AJAX call. In my PHP file I put the id's in a delete query to delete records from my database. How can I do this? I tried several things like mapping it to an array or converting to an JSON but I cant seem to get it to work. In my PHP I get undefined or empty arrays.
HTML:
<button href="" id="deletebutton" type="button"
class=""
disabled="">Delete
</button>
<input type="checkbox" class="checkbox-clicks" id="" name="" value="1001">
<input type="checkbox" class="checkbox-clicks" id="" name="" value="1002">
JQuery:
$("#deletebutton").on("click", function() {
var results = {}; // <== object
var data = JSON.stringify(results);
var checkedIds = $(".checkbox-clicks:checked").each(function() {
results['id'] = this.value;
});
$.ajax({
url:"testurl",
type: "POST",
data: data,
success: function (result) {
console.log('succesful delete');
},
error: function (xhr, status, error) {
console.log('unsuccesful delete');
}
});
}
PHP:
$request = $_POST;
$ids = json_decode($request);
$req = $ids->id;
$conditions = array(
$db->quoteName('person_id') . " = " . $req,
);
$query->delete($db->quoteName('mydb'));
$query->where($conditions);
How can I put id 1001 and 1002 in the same query as a condition?
You're currently passing the data (values from the checkbox) from your original page, through jQuery, to your 'testurl' page.
Instead, you can get the values directly on your 'testurl' PHP page from the $_POST data.
On your first page, be sure to define the checkbox names, so you can reference them on the backend:
foreach($personid as $value) {
echo '<input type="checkbox" name="personid[]" value= "'.$value.'">'.'<br>';
}
PHP for your listener page:
<?php
// Listen for post
if ( isset($_POST) ) {
if(!empty($_POST['personid'])) {
foreach($_POST['personid'] as $value){
// Do your DB query here with condition looking at $value
}
}
}
?>