JQuery Switching and Transferring Data

I created a toggle button with jquery, but I need to pass my $id so that it can execute mysql in toggle_visibility.php .

How to pass my variable from the <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> 
+4
source share
1 answer

It looks like $id is a PHP variable, so when the server creates your page, it will print in the right place.

But you are missing = in the line:

 data: "id=<?= $id ?>", 

If this is not what you want, you need to clarify where $id comes from.

Update:

You need to somehow integrate the identifier in the row of the table. For instance. you can set the 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 get it in a function using the jQuery 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"); } ); 
+4
source

Source: https://habr.com/ru/post/1307259/


All Articles