One checkbox
<input id='fuckyeah' type='checkbox' value='1'>
checkbox = document.querySelector('#fuckyeah'); checkbox.onchange = function() { $.ajax({ url: 'index.php', type: 'POST', data: { settings: 0, id: this.value, checked: this.checked ? 1:0 }, beforeSend: function() { checkbox.disabled = true; }, complete: function() { checkbox.disabled = false; }, success: function(response) { console.log(response); } }); }
if(isset($_POST['settings'])) { $checkbox = (int) $_POST['id']; $checked = (int) $_POST['checked']; settingsUpdate($checkbox, $checked); } function settingsUpdate($checkbox, $checked) { $query = mysql_query("UPDATE settings SET status = '$checked' WHERE id = $checkbox"); if(!$query) echo 'err'; }
Several checkboxes
value id input
name settings name
<input class='fuckyeah' type='checkbox' value='1' name='settings'> <input class='fuckyeah' type='checkbox' value='2' name='settings'>
checkboxes = Array.from(document.querySelectorAll('.fuckyeah')); checkboxes.forEach(function(checkbox, i) { checkbox.onchange = function() { $.ajax({ url: 'index.php', type: 'POST', data: { settings: this.name, id: this.value, checked: this.checked ? 1:0 }, beforeSend: function() { checkbox.disabled = true; }, complete: function() { checkbox.disabled = false; }, success: function(response) { console.log(response); } }); } });
if(isset($_POST['settings'])) { $settings = (string) $_POST['settings']; $checkbox = (int) $_POST['id']; $checked = (int) $_POST['checked']; settingsUpdate($settings, $checkbox, $checked); echo 'id: '.$checkbox.', status: '.$checked; } function settingsUpdate($settings, $checkbox, $checked) { $query = mysql_query("UPDATE $settings SET status = '$checked' WHERE id = $checkbox"); if(!$query) echo 'err'; }
data_base_name database name
table_name name of the table, in this case, settings
$query = mysql_query(" CREATE TABLE IF NOT EXISTS `data_base_name`.`table_name` ( `id` INT NOT NULL AUTO_INCREMENT , `checked` INT NOT NULL , PRIMARY KEY ( `id` ) ) ENGINE = MYISAM ; ");
ifgo into javascript? Does the PHP script itself start running? Does the browser console write any errors (usually caused by pressing F12)? - yeputons$(this).attr("value");- it is more correct to use$(this).val();andWHERE id_test = $id_testshould beWHERE id_test = '$id_test'- Alexvalueis not a checkbox status, always one is sent. At the output of php, the answer is returned for some reason in the form ofjson_encode, whenadd_checkedreturns only(boolean) true- Mr. Black