title: How to use ajax to update mysql db when checkbox condition is changed?
body: <p>I have a table of articles that displays in rows on client side. Each articles has a unique id and contains a checkbox to indicate if this article is checked as a favorite. If it is a favorite, then the checkbox is already checked. If not, it is unchecked. Now I need either js or jquery and ajax to update the table in the DB if and when the checkbox condition changes specific to each row. Another challenge is that I am working in cakePHP MVC environment.</p>
  
  <pre><code>&lt;script type="text/javascript" src="jquery-1.2.1.min.js"&gt;&lt;/script&gt;
  &lt;script type="text/javascript"&gt;
  
      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 + '&amp;amp;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 + '&amp;amp;favorite=0',
              });
          }//else
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>--html-- this is within a foreach loop.</p>
  
  <pre><code>echo "&lt;input type='checkbox' id='$rowid;' name='favorite' checked='checked' onclick='checkbox_click('id','favorite',this();' /&gt;";
  
  
  else
  echo "&lt;input type='checkbox' id='$rowid;' name='favorite'  onclick='checkbox_click('id','favorite',this.checked);' /&gt;";
  </code></pre>
  
  <p>--php file called by ajax--</p>
  
  <pre><code>&lt;?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);
  ?&gt;
  </code></pre>