lundi 19 janvier 2015

How to Update Checkbox DB value using AJAX

I'm new to AJAX and trying to teach myself so I've started with a seemingly simple example. I'm echoing out all the rows in the DB and I have a checkbox, that when checked I'd like to have its value updated in the DB. Here's what I have so far.



<html>
<script src="http://ift.tt/1yCEpkO"></script>
<script>
$('input[name=checkbox]').click(function(){
var id=$(this).attr('id');
var checkbox=$(this).val();
$.ajax({
type:'POST',
url:'check_checkbox.php',
data:'id= ' + id + '&checkbox='+checkbox
})
.done(function( response ) {
alert(response );
)};
</script>
<?php
require('connection.php');
$mysqli = new mysqli($hostname,$username,$password,$database);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$results = $mysqli->query("SELECT * FROM chkDatabase");
echo '<table border=1 cellpadding="10 cellspacing="1 style="background-color:#F0F8FF; margin: auto;"';
echo '<tr>';
echo '<th>ID</th>';
echo '<th>User ID</th>';
echo '<th>Checkbox</th>';
while($row = $results->fetch_array()) {
echo '<tr>';
echo '<td>'.$row["id"].'</td>';
echo '<td>'.$row["userid"].'</td>';
echo '<td><input type="checkbox" name="checkbox" value=" '. $row['checkbox'] .'"/></td>';
echo '</tr>';
}
echo '</table>';
$results->free();
$mysqli->close();
?>


check_checkbox.php



<html>
<?php
$id=$_POST['id'];
$checkbox=$_POST['checkbox'];
require('connection.php');
$mysqli = new mysqli($hostname,$username,$password,$database);
if ($mysqli->connect_error) {
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
$sql = "UPDATE chkDatabase SET checkbox='$checkbox' WHERE id='$id'";
if ($mysqli->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $mysqli->error;
}
$mysqli->close();
?>
</html>


I'm using tinyint for the checkbox value. I've been able to find convoluted examples online but I can't seem to figure out what I need to get this working as nothing happens when I click on a checkbox. Any assistance is greatly appreciated.





Aucun commentaire:

Enregistrer un commentaire