0

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.

1
  • Does your second one include the div as well? You can also directly echo the string out into the javascript code as follows: $.prompt('<h3 Store unavailable</h3><?php echo STORE_OFFLINE_MSG;?>'); Commented Jul 4, 2013 at 8:35

2 Answers 2

4

You can store the variable directly in javascript variable.

<script type="text/javascript">
   var msg = "<?php  echo STORE_OFFLINE_MSG;?>";
Sign up to request clarification or add additional context in comments.

1 Comment

it's fine if it's just a constant, but don't put any user data in JS - it's a perfect place for XSS attacks.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.