views:

136

answers:

1

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 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>
+2  A: 

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");
     }
);
Felix Kling
the id comes from the database, there are 10 rows and this $id needs to be passed from the <A> tag. The line was wrong but that is not the problem. <a class="toggleVisibility" href="?id=<?php print $id;?>">Yes</a> I would usually do it using $_GET like this, but how do I pass it to the jquery function?thanks.
Ross
@Ross: Can you please show your HTML markup for the table? I assume you also show the ID in a cell. Basically you have to get the ID from there.
Felix Kling
pasted below, it is a php while loop that output the rows of the table<?phpwhile($row = mysql_fetch_array($result)) { ?> <tr> <td class="date"><?php print $row['date']; ?></td> <td><?php print $row['title']; ?></td> <td class="visible"><a class="toggleVisibility()" </a></td> <td class="modify"><a href="editnewsitem.php?id=<?php print $row['id']; ?>"><img src="img/modify_icon.gif" alt="modify" width="13" height="15" /></a> </td> </tr><?php }?>
Ross
@Ross: See my updated answer.
Felix Kling