简体   繁体   中英

Passing PHP variable in JS using div id

I have some pages. In these pages i want to show the error message. Now i am showing these message through JavaScript.But the code is repeated so many times that's why i have decided to define this message as a constant in config file.

I accessed this constant STORE_OFFLINE_MSG in a div. And then I am using the html of this div , this function return the text of the div as defined in config file and passes it in the variable of JS this is the code in my config file config.php:

  define('STORE_OFFLINE_MSG','hello');

This is the sort of code of php file abc.php

<div class="storeOfflineMsg"><?php  echo STORE_OFFLINE_MSG;?></div>
<script type="text/javascript">
  var msg = $(".storeOfflineMsg").html();
  $.prompt('<h3 Store unavailable</h3>'+msg);
</script>

but if i used this variable in other file only by using the div class then .html() returns NULL.

My second file xyz.php is as:

<script type="text/javascript">
  var msg = $(".storeOfflineMsg").html();
  $.prompt('Store unavailable</h3>'+msg);
</script>

Please suggest me what to do. and how can i get a php constant in the Java Script through div class.

You can store the variable directly in javascript variable.

<script type="text/javascript">
   var msg = "<?php  echo STORE_OFFLINE_MSG;?>";

If you want to pass data from PHP to Javascript try this:

echo the data out in the of your page within a script section.

<script type="text/javascript">
<?php
   echo 'var offlineMsg = ' . STORE_OFFLINE_MSG . ';';
   echo 'var onlineMsg = ' . STORE_OnLINE_MSG . ';';
?>
</script>

These Javascript variables will then be availabe globally to all other javascript code on the page. Much better than placing it in a hidden 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