hunter
hunter

Reputation: 1101

how to update and post the value of checkbox from ajax call

i retrieved data from mysql table into html page 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[]" <?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>

this is gives me the output enter image description here

assume that checkbox of id 1 is checked and retrieved from mysql table.
Now what i want to do is that when i checked the remaing two checkbox into this table and a function is called to ajax which goes to php page and update the value of checked field according to the given id (i.e 2 and 3 in this case). Not refreshing the whole page nor updating the whole record just the value of check box.
i am new to ajax so any help would be greatly appreciated.

Upvotes: 0

Views: 4373

Answers (1)

Robin Maben
Robin Maben

Reputation: 23034

Yes, exploring jqGrid isn't a waste of time at all. However, since you want to update only on change of checkbox value. Here's what you can do..

<input type="checkbox" name="check1"  />

And..

$().ready(function(){
  var st_id = <?php echo $rs['st_id']; ?>;
  //Or you could use a hidden field in the form

  $(':checkbox').click(function(){
    var chkName = $(this).attr('name');
    var checkVal = $(':checkbox[name='+chkName+']').attr('checked');//true or false
    $.ajax({
      url: 'MyApp/update.php?checboxName=' + checkVal,//Do update on server-side
      success: function(data) {
        alert('Updated successful.');
      }
    });
  });
});

Also, you can do a $('formID').serialize() wihch returns name=value pairs of all form elements that can then be appended in the call to your php script.

Upvotes: 1

Related Questions