'JavaScript loading depending on PHP [duplicate]
I have a PHP 'if' that only loads a certain JavaScript if it is applicable:
(this is from the <head> of my page):
<?PHP if ($row['jstype'] == 'myanswer')
{
echo '<script type="text/javascript" src="js/index.js"></script>';
}
else
{
echo '';
}
?>
Now, I have checked the source on a page that it applies to and the js appears in the html. However, it is not loading. I can only assume that this is because it is not loading with enough time after getting it's instruction from the PHP. Is this a correct assumption?
And, more importantly, can anyone suggest a way of doing what I need it to do?
Solution 1:[1]
set up a test file index.js containing only:
alert('boo!');
Test that works with a hard-coded version of your js include line.
Prove it works.
Then add your PHP version.
PHP spits out the whole stream to the browser, so no, its nothing to do with PHP - probably something to do with relative/absolute paths in the SRC of the js defn - hence the incremental development idea above should help identify where you are going wrong. Divide and conquer.
The code you showed means there is no point in having an else, so you could shorten it to:
<?php
if ($row['jstype'] == 'myanswer')
echo '<script type="text/javascript" src="js/index.js"></script>';
?>
Depending on how many ELSE conditions you actually do need, show them and its possible someone can suggest better ways of writing it.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cups |
