Jquery Toggle & passing data
I have created a toggle button with jquery but I need to pass my $id
so it can execute the mysql in toggle_visibility.php
.
How do I pass my variable from my <A>
tag ?
<a class="toggleVisibility">Yes</a>
<script>
$("a.toggleVisibility").toggle(
function () {
$(this).html("No");
},
function () {
$.ajax({
type: "POST",
url: "toggle_visibility.php",
data开发者_高级运维: "id<?=$id; ?>",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(this).html("Yes");
}
);
</script>
It looks like $id
is a PHP variable so when the server generates your page it will be printed at the right spot.
But you are missing a =
in the string:
data: "id=<?= $id ?>",
If this is not what you want you have to clarify where $id
comes from.
Update:
You have to integreate the ID somehow in the table row. E.g. you could set is as rel
attribute for the link:
<tr>
<td class="date"><?php print $row['date']; ?></td>
<td><?php print $row['title']; ?></td>
<td class="visible">
<a class="toggleVisibility" rel="<?php echo $row['id']; ?>">Toggle</a>
</td>
</tr>
then you can fetch it in the function with jQuery's attr()
method:
$("a.toggleVisibility").toggle(
function () {
$(this).html("No");
},
function () {
$.ajax({
type: "POST",
url: "toggle_visibility.php",
data: "id=" + $(this).attr('rel'),
success: function(msg){
alert( "Data Saved: " + msg );
}
});
$(this).html("Yes");
}
);
精彩评论