- How to use ajax to update mysql db when checkbox condition is changed?
- <script type="text/javascript" src="jquery-1.2.1.min.js"></script>
- <script type="text/javascript">
- function checkbox_click (id, favorite)
- {
- // see if checkbox is checked
- if(favorite==1)
- {
- $.ajax({
- type:'POST',
- url:'check_favorite.php', // this external php file isn't connecting to mysql db
- data:'id= ' + id + '&favorite=1',
- });
- }// if
- // the checkbox was unchecked
- else
- {
- $.ajax({
- type:'POST',
- url:'check_favorite.php', // this external php file isn't connecting to mysql db
- data:'id= ' + id + '&favorite=0',
- });
- }//else
- }
- </script>
- echo "<input type='checkbox' id='$rowid;' name='favorite' checked='checked' onclick='checkbox_click('id','favorite',this();' />";
- else
- echo "<input type='checkbox' id='$rowid;' name='favorite' onclick='checkbox_click('id','favorite',this.checked);' />";
- <?php
- //Database Variables - with the variables entered it doesn't connect
- $dbhost = 'localhost'; // usually localhost
- $dbuser = 'username'; // database username
- $dbpass = 'password'; // database password
- //Establish connection to MySQL database
- $con = @mysql_connect($dbhost, $dbuser, $dbpass);
- if (!$con)
- die('Unable to connect.' . mysql_error());
- mysql_select_db('devcake', $con);
- // Get the variables.
- $query = "UPDATE mytable SET favorite=".$_POST['favorite'] . "
- WHERE id=".$_POST['id'] . ";";
- mysql_query($query);
- mysql_close($con);
- ?>
- $dbhost='localhost';
- $dbuser='root';
- $dbpass='';
- $id=$_POST['id'];
- $favorite=$_POST['favorite'];
- $query="UPDATE mytable SET favorite='$favorite' WHERE id='$id'";
- echo "<input type='checkbox' id='$rowid;' name='favorite'";
- if(//check in database if 'favorite' column is set to 'on'){
- print "checked='checked'";
- }
- echo "/>";
- $('input[name=favorite]').click(function(){
- //if a checkbox with name 'favorite' is clicked, do the following.
- //grab the id from the clicked box
- var id=$(this).attr('id');
- //grab the value from the checkbox (remember, if it is checked it will be 'on', else ''
- var favorite=$(this).val();
- //setup the ajax call
- $.ajax({
- type:'POST',
- url:'check_favorite.php',
- data:'id= ' + id + '&favorite='+favorite
- });
- }
- });
- echo "<input type='checkbox' id='$rowid;' name='favorite' checked='checked' onclick='checkbox_click('$rowid','favorite',this();' />";
- else
- echo "<input type='checkbox' id='$rowid;' name='favorite' onclick='checkbox_click('$rowid','favorite',this.checked);' />";