hunter
hunter

Reputation: 1101

post and update value of checkbox using ajax

based on my yesterday post how to update and post the value of checkbox from ajax call i changed my code to this i.e

$query="select * from student";
$result=mysql_query($query)or die(mysql_error());
while($rs=mysql_fetch_array($result))
{
?>
<tr>
      <td align="center"><?php echo $rs['st_id']; ?></td>
<td align="center"><?php echo $rs['name']"; ?></td>
<td align="center"><input type="checkbox" name="checked" onclick="UpdateCheckBox()" <?php if($rs['checked']==1){echo "checked"; } ?> /></td>
<td align="center"><a href="delete_student.php?id="><img src="images/delete_icon.png" alt="Delete" /></a></td>
<td align="center"><a href="update_student.php?id="><img src="images/update.png" alt="Update" /></a></td>
</tr>
<script type="text/javascript" src="jquery.js">
    function UpdateCheckBox()
{
   var st_id = <?php echo $rs['st_id']; ?>;
    $('input[type=checkbox]').click(function(){
    var chkName = $(this).attr('name');
    var checkVal = $(':checkbox[name='+chkName+']').attr('checked');//true or false
    $.ajax({
      url: 'update.php?checboxName=' + checkVal,//Do update on server-side
      success: function(data) {
        alert('Updated successful.');
      }
    });
  });
}
    </script>
  <?php
  }

   ?>
    </tbody>
</table>

my update.php code is

$conn=new LoginSystem();
$conn->connect();
$update=$_GET['checboxName'];
$sql="UPDATE student SET checked='$update'";
$rs=mysql_query($sql);
?>

when i clicked on the checkbox nothing is happen and when refresh the whole page it is automatically unchecked. Note that there is no form or submit button all thing is done on checkbox on click event. I want to update the database by clicking on checkbox in populated table. any help please

Upvotes: 1

Views: 3701

Answers (1)

Dan Grossman
Dan Grossman

Reputation: 52372

We can't tell you why update.php isn't working since you didn't share that code. Right now, it can't possibly work, as you're not providing it with any way to know what row to update and whether the box was checked or not.

You need to give the checkboxes in each row different names so that you know which one was checked in your PHP code. Use the row's identifier in the name, like checkbox_3 or checkbox[3]. Then you need to make sure you make the checkbox's value part of the URL as well.

Upvotes: 0

Related Questions