简体   繁体   中英

how to store php variable passed as id to javascript in a javascript variable

I am trying to pass div id to javascript and print it out on console as :

<?php echo 67;?>

The 67 is id here. I was wondering how can I store this value in my javascript variable storeid as var storeid = 67 ?

My code:

 echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";

        echo "<script>

        $('h2.editme').click(function(){
            console.log(this.id);
            var storeid;

        });

        </script>";

Also, I want to use that id value to update the values in my sql. I can only test my code once I could somehow get the value of that id. How can I store the value of the id to javascript variable?

My code (This is to update sql once I get the id) - Not sure if it's right I can test it after getting id value:

 echo "<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>";

            echo "<script>

            $('h2.editme').click(function(){
              var content2 = $(this).html();

                console.log(this.id);
                var storeid;//once I get the id
 $.ajax({
                      url: 'updateDescription(storeid, content2)',
                      success: function(respon) {
$('.editme').html(respon);
                      }
                    });

            });
   
            </script>";

function updateDescription($user_unique_id, $content2)
{
    try {
        require "testing.php";
        $sql = "UPDATE icecream  SET
             desc = :desc
             WHERE id = :id";
        $stmt->bindParam(':desc', $content2, PDO::PARAM_STR);
        $stmt->bindParam(':id', $user_unique_id);
        $stmt->execute();
        echo 'Record updated';
    } catch (PDOException $e) {
        echo 'Connection failed ' . $e->getMessage();
    }

}

this way:

echo '<script>
   var storeid = '. $id .'
 </script>';

more readable way:

// somefile.php
<?php

   $id = 67;

?>

<h2 class='editme' id='<?php echo $id;?>' contentEditable='true'> Hello</h2>

<script>
  var storeid = <?php echo $id; ?>
  // rest of javascript code
</script>

<?php
 // rest of the php code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM