Friends,
I want to call a PHP function with AJAX and then capture the return value of the PHP so I can do stuff based on the response. Here is how it looks like. First of all with JS I find all checkboxes in the document by specific name and for each of them I call a PHP function ‘check’. This function searches in the database whether the checkbox with the provided value exists or not. If it exists, the PHP function returns true, otherwise false. When its back to JS I want to check that checkbox if true was returned. The code:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
checkboxes.forEach(function(checkbox) {
if ((checkbox.name=='ColSelect')){
jQuery.ajax({
url: "<?php echo admin_url('admin-ajax.php');?>",
type: "POST",
data:{
action: 'check',
chBoxes: checkbox.value,
},
success: function (data) {
}
});
}
Then a PHP function:
function check()
{
global $wpdb;
$chBoxes = esc_sql($_POST['chBoxes']);
$existingItems=$wpdb->get_var("SELECT items FROM orders");
$items = explode(" ", $existingItems);
foreach ($items as $item) {
if ($item == $chBoxes)
return 1;
}
return 0;
exit;
}
add_action('wp_ajax_check_checkboxes', 'check_checkboxes');
add_action('wp_ajax_nopriv_check_checkboxes', 'check_checkboxes');
How can I handle the return from the PHP function in the AJAX call? In case 1 is returned, I would then do something like: checkbox.prop("checked", true);
Thanks.