简体   繁体   中英

How to convert and transmit PHP Variable data Using JSON to HTML page's Javascript

I can't seem to figure it out how to convert the following PHP variable to HTML:

$persondata = "<div id='teach'><h3>Name: " . $row["fname"]. "<br>User Name: " . $row["username"]. "</h3><p>Password: " . $row["upass"]. "</p></div><br>";

I wanted to pass that exact data to my HTML page, so that I can use JavaScript's getElementById function to insert it into a selected data field.

I asked a similar question here , which helped me work out some of logic I need, but I can't work out this part of the equation.

If you could please let me know of a simple way of going about this, it would be very much appreciated, as I don't even know the keywords to search for.

A javaScriptVar equals with an echo in php of your php variable.

That is to put php inside js

<script type="text/javascript">
//Your JS

var jsvar = <?php echo $persondata; ?>

//Your JS
</script>

Put PHP var like above into js.

Continuing from above answer:

That is to put php inside js

<script type="text/javascript">
//Your JS

var jsvar = <?php echo $persondata; ?>;

//Your JS
</script>

Put PHP var like above into js.

If you want to transmit data from a PHP script in a server to a client side HTML page for using in js. Go like following.

  1. First get all your data in PHP in an array and use json_encode() and after that echo that variable.
  2. Now in the client side HTML use jQuery.ajax() and send request to that PHP file in server.
  3. When you have the response in Json use js to fragment it and append wherever you want.

Above is the basic procedure to send data from PHP to HTML page using JS.

Hope below code help you:

<?php
$persondata = '';
foreach($rows as $row){
 $persondata .= "<div class='teach'><h3>Name: " . $row["fname"]. "<br>User Name: " . $row["username"]. "</h3><p>Password: " . $row["upass"]. "</p></div><br>";
}

?>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
      $(document).ready(function () {
         $('#data-row').html("<?php echo $persondata ?>");
      });
    </script>
</head>
<div id="data-row"></div>

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