I have a table where a user clicks on image to block/unblock user. which is something like this.

the html for the table (including the column for block/unblock) is retrieved via AJAX as i am using the jquery data table plugin.
here is the retrieved html for the column block/unblock
<td>
<a class="toggle" href="#toggle">
<img src="app/css/images/tick.png" alt="Yes" data-id="4" data-block="0">
</a>
</td>
the data-table block represents the state of block/unblock, if the value is 0 then it shows an image called tick.png (enabled) else tock.png(disabled).
i am using the following jQuery to capture the click and send data to server side to get and make changes.
$('.toggle').live('click', function() {
var id = $(this).find('img').data('id');
var block = $(this).find('img').data('block');
$.ajax({
type: 'POST',
url: "app/ajax/User/Block.php",
data: 'id='+id+'&block='+block,
success: function(data) {
var image = (data == 1) ? 'app/css/images/tock.png' : 'app/css/images/tick.png';
$('.toggle img[data-id="'+id+'"]').attr('data-block', data);
$('.toggle img[data-id="'+id+'"]').attr('src', image);
}
});
});
and here is the PHP code i am using.
if(isset($_POST['id']) && isset($_POST['block'])) {
$userId = $_POST['id'];
//$_POST['blocks'] holds the current value of block/unblock.
//toggle the block/unblock state.
$block = $_POST['block'] == 1 ? 0 : 1;
User::blockUser(array($userId), $block);
//Respond back toggled block/unblock value.
echo $block;
}
everything works fine if i click the image toggles the state so as the data-block value get updated, the problem is i can click it only once, if i click the same image again it doesn’t do anything. i checked the values in console, the values does not get updated too after the first click. what is wrong with the code?
Update :
Here is the HTML in the first stage before i.e before clicking.
<a class="toggle" href="#toggle">
<img src="app/css/images/tick.png" alt="Yes" data-id="4" data-block="0">
</a>
here is the HTML after clicking the same row.
<a class="toggle row_selected" href="#toggle">
<img src="app/css/images/tock.png" alt="Yes" data-id="4" data-block="1">
</a>
//Here the extra class row_selected is added by default by another plugin, do you think this is creating the problem?
and here it is again after first click.
<a class="toggle" href="#toggle">
<img src="app/css/images/tock.png" alt="Yes" data-id="4" data-block="1">
</a>
jQuery has its own data implementation:
You should use
.data('block', data);instead of.attr('data-block', data);as you read it with
$(this).find('img').data('block')Also you shouldn’t use jQuery for class detection like
$('.toggle')if you know the tag.In your example you could easily improve the performance by using
$('a.toggle')