Getting PHP variable in jQuery

So, I have this:

<?php
 echo '
  <script>
$(function(){
   $("a#yeah").click(function(){
           $.ajax({
        url: "ajax.php?action=yeah&id='.$id.'",
        success: function(html){
         $("a#yeah").html("your cool")
                   }
     })
   })


})</script>';

?>

I mainly use the PHP variable $ id, which can be found in the document, how can I get the same variable but not repeat jQuery (so that I can preserve editor syntax highlighting in the Javascript part)?

+3
source share
3 answers

never repeat the code on the client side - just enter it as is. PHP is especially good at this http://www.php.net/manual/en/language.basic-syntax.phpmode.php

  <script>
$(function(){
   $("a#yeah").click(function(){
           $.ajax({
        url: "ajax.php?action=yeah&id=<?php echo $id?>",
        success: function(html){
         $("a#yeah").html("your cool")
                   }
     })
   })


})</script>
+9
source

You can add php inline, for example:

<script> var yourVariable = '<?php echo $phpVar; ?>'; </script>
+7
source

, , :

      ...stuff...
      url: "ajax.php?action=yeah&id=<?=$id?>",
      ...more stuff...

short_open_tag, <?php echo $id; ?>

0

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


All Articles