I have an application where a user would check off an input checkbox and that value would be sent to the database without reloading the page; which it does. However, when I uncheck that same element its hidden type; which contains a value of 0, is not submitted, instead, it still submits the value of 1 from the checkbox.
Inputs are created dynamically:
function build_something(it, src){
var something = it;
var htag = it+"-header";
var ctr = document.createElement('div');
ctr.setAttribute('class', 'interest_container');
var lbl = document.createElement('label');
lbl.setAttribute('for', something);
var img = document.createElement('img');
img.setAttribute('src', src);
var title = document.createElement('h2');
title.setAttribute('id', htag);
var inp_f =document.createElement('input');
inp_f.setAttribute('type', 'hidden');
inp_f.setAttribute('name', something);
inp_f.setAttribute('value', 0);
var inp = document.createElement('input');
inp.setAttribute('type', 'checkbox');
inp.setAttribute('id', something);
inp.setAttribute('name', something);
inp.setAttribute('value', 1);
lbl.appendChild(img);
ctr.appendChild(lbl);
ctr.appendChild(inp_f);
ctr.appendChild(inp);
ctr.appendChild(title);
var elem = document.getElementById('idk');
elem.appendChild(ctr);
document.getElementById(htag).innerHTML = it;
}
Binds nearest element grabs input and onchange post checked element:
$('#interests').on('change', 'input', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'some.php',
async: true,
data: $(this).serialize(),
success: function (msg) {
console.log(msg);
}
});
})
storeData is a function called by some.php:
function storeData($form_data, $table_name, $cxn){
if(!is_array($form_data)){
return false;
exit();
}
$types = str_repeat("s", count($form_data));
$params = array();
$params[] = &$types;
$keys = array_keys($form_data);
$values = array_values($form_data);
for ($i = 0; $i < count($values); $i++) {
$params[] = &$values[$i];
}
$sql = "INSERT INTO $table_name (" . implode(',', $keys) . ") VALUES (" .
implode(',', array_fill(0, count($values), '?')) . ")
ON DUPLICATE KEY UPDATE ";
$updates = implode(',', array_map(function($col) {
return "$col = VALUES($col)";
}, $keys));
$sql .= $updates;
$stmt = mysqli_prepare($cxn, $sql);
call_user_func_array(array($stmt, 'bind_param'), $params);
return mysqli_stmt_execute($stmt);
}
when I check the input box it submits the value and stores it; however, when I uncheck that same element it should send a value 0 but it doesn't.
EDIT: my issue is different because the other solution suggestion a dropdown. I do not want that.