I need a checkbox to update a MySQL field from a 1 to 0 and vice versa when clicked. I want to use jQuery/AJAX and PHP to do this so I do not have to have the page re-loaded. I placed the code below but I cannot get it to work. I feel that I am very close.
Note: I know mysql_query
is deprecated. This is an older project and I will be converting it soon but need this to work for now.
The form:
if($list_row['online'] == 0) {
echo '<input type="checkbox" name="online" id="' . $list_row['id'] . '" data-toggle="toggle" checked> ';
} else {
echo '<input type="checkbox" name="online" id="' . $list_row['id'] . '" data-toggle="toggle"> ';
}
The jQuery:
<script>
$('.online').mousedown(function() {
var id = $(this).attr('id');
if($(this).attr('checked')) {
var online = 1;
} else {
var online = 0;
}
$.ajax({
type:'GET',
url:'processes/process_item_online.php?',
data:'id= ' + id + '&online='+online
});
});
</script>
The PHP:
include '../connect.php';
// START IF LOGGED IN
session_start();
if (!isset($_SESSION['is_logged_in'])) {
header("location: login.php");
} else {
$login = true;
}
$id = $_GET['id'];
$online = $_GET['online'];
mysql_query("UPDATE `store_items` SET online=$online WHERE id='$id'");
Problem solved by using the $(document).ready(function() {
code before the jquery.