Question

I am trying to clean up my pages, and one of the major ways that I am doing so is to put JavaScript and JQuery functions into a file called 'scripts.js' that is automatically accessed upon page load.

I've run into a problem with functions that use php to call from the page itself. For example, the following function doesn't work, and in fact 'kills' the script for all pages (so now things that were supposed to be hidden are not, and things are not loading properly). I've narrowed it down to the fact that I use to call a variable. I would really like to be able to keep functions using PHP in this universal file as opposed to clogging up the HTML template pages, any thoughts on either how to make this work, or if not how else I may be able to call the values needed? They are always extracted to the page before rendering if that helps.

function positiveSelect()
{
   var size = <?php echo $idea[0]["size"]; ?> * 1;
   if (size > 5)
      return true;
   else
      return false; 
}
Was it helpful?

Solution

if you can't retrive your data form the DOM itself you can store values with the corresponding object:

 <div data-size=20>

and then retrive it with:

 $(element).data("size");

or if you have global data you want to store you can create a value "container" in the head of you html document like this:

<script type="text/x-json" class="global-data">{"value1":"1","value2":"2"}</script>

and then read the content of that element and parse it with JSON.parse

OTHER TIPS

If this function is that specific to a certain page, you might want to add a second js script that just gets loaded on that page.

An alternative would be to echo out a js variable in that php page and have your code call that function with that variable as a parameter.

You can give the javascript a ".php" extension and call it in the script in the same exact way:

<script type="javascript" src="path/to/scripts.php"></script>

You could just name the generate scripts file scripts.php or scripts.js.php; then the PHP preprocessor will process the file and the PHP statements will be evaluated.

When mixing php or any server side language with javascript you need to be aware that the php gets executed only once when the javascript file is created on the client side.

This is probably why you are getting unexpected results. As you move from page to page the php snippet in your global scripts.js will not get updated.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top