I have a JavaScript which is currently being re-used in over 5 websites, and will prolly be used by alot more websites as time progresses, the thing is - that javascript runs some checks according to the server name, and I was wondering what's the best way to create some JS file which has some server side variables in it, such as:
js-functions.php:
<script type='text/javascript'>
var myServer = <?php echo $_SERVER['SERVER_NAME'] ?>;
</script>
as currently, this file will be downloaded every time, so how can I make it send out a 304 Unmodified, and use the browser caching to my advantage
Use .htaccess
RewriteEngine on
RewriteRule javascript.js javascript.php [L]
Name your php file javascript.php and direct your requests to javascript.js
Note: You need to set correct cache headers in your php file before sending any output
I would not create a dynamic JS file at all. If at all possible, put all the dynamic stuff into the main document; then load the main chunk of JavaScript from a static resource.
Put the code you already have into the head section of each HTML page:
<script type='text/javascript'>
var myServer = "<?php echo $_SERVER['SERVER_NAME'] ?>";
</script>
then link to a static JavaScript file:
<script src="http://domain.com/js/script.js">
inside the JavaScript file, do not use any PHP; use the myServer variable to do your checks.
The advantage of this is that if the web server is configured correctly, the static JS file will be loaded only once and you don't have to worry about caching.
You could even share the same JavaScript URL between all 5 sites.
Related
Actually i am writting a php script to link some javascript files in my multiple sites.
Example : site_dir1/js/jquery.1.4.2.js and
site_dir2/js/jquery.1.4.2.js
In this case, in the document_root location i have a file called "jquery/jquery.inc.php which has the follwing code
$jq_142 = "<script type='text/javascript' language='JavaScript' src='jquery-1.4.2.min.js'></script>";
I will use this code to make require my php file anywhere i want
<?php require $_SERVER['DOCUMENT_ROOT'].'/jquery/jquery.inc.php' ?>
And the reputation of jquery file keeps only one copy in my following location.
$_SERVER['DOCUMENT_ROOT'].'/jquery'
My doubt is still my javascript files are not loaded where ever i call the files.
I am little messed. how to fix it? any better solution?
If you're going to do this you need to give the script an absolute path rather than a relative one.
When you include it in index.php, the browser will look at /jquery.js for the file. When you include it in /folder/page.php, the browser will look check /folder/jquery.js.
See how it changes depending on where you are in the website? You need to tell it to look at a specific place, like:
$jq_142 = "<script type='text/javascript' language='JavaScript' src='http://example.com/scripts/jquery-1.4.2.min.js'></script>";
This means that no matter where you are in your site, the browser will check http://example.com/scripts/jquery-1.4.2.min.js for jQuery.
Finally, I found my page.php script have loaded my jquery.inc.php file. But the jquery file linking script has been coded inside quotes as follow :
$jq_142 = "<script type='text/javascript' language='JavaScript' src='jquery-1.4.2.min.js'></script>";
So it's couldn't be displayed. And i found this jquery.inc.php is not called by .html files. Only for .php files. I couldn't find any alternative solution for this problem.
I have linked by using the absolute path of my unreplicated jquery library files from jquery/jquery-xxx.js directly.
I've got this javascript code:
$(document)
.load(function(){
$.post(
'result_source.php?term='+<?php echo $_REQUEST['term']; ?>
);alert('abc123');
});
and it doesn't alert('abc123');. If I remove the
+<?php echo $_REQUEST['term']; ?>
it does alert('abc123').
Thanks
You need to take the PHP part out of the concatenation. The PHP is effectively pasted in to the javascript page before it is processed, so unless your $_REQUEST['term'] is the name of a javascript variable you are using, it will cause errors.
Change it to: $(document).load(function(){$.post('result_source.php?term=<?php echo $_REQUEST['term']; ?>');alert('abc123');});
Bear in mind this won't work inside external javascript files, unless you create an .htaccess or something to configure the server so it parses .js files as PHP before outputting to the browser
PHP will not run in an external JavaScript file unless you create a .htaccess file or configure the server so it parses .js files as PHP before outputting to the browser.
If you put that in a file(with a .php extension), in <script> tags, it will work, though.
I have this change request to move all my inline javascript to an external file. I tried a simple copy-paste to a new file, but no luck. I'm getting error at the following line:
var grp_list = <?php echo json_encode($arr_grp); ?>; and
url: "<?php echo $_SERVER['PHP_SELF']; ?>"
I have atleast 20 such occurrences. How do I replace these php variables in external javascript??
I checked lot of forums but did not find any solution.
Thanks a lot for your help!!
Well, you have JavaScript dinamically "assembled" in your PHP script. The easiest solution is to forget about translating the variables. Instead, put all JS code, including the PHP portions, in a PHP file which will pretend to be a JS file, using a custom header. So, your "JavaScript" file will be like this:
<?php
// Send a custom header, so that it will be interpreted as a js file.
header("Content-Type: application/javascript");
?>
JavaScript and PHP mixed code will go in here, with no modifications
Save this file as something like "javascript.php". Then, in your main HTML or PHP file, include it as:
<script src="javascript.php"></script>
That's it! The javascript.php file will be interpreted as a PHP file in the server and retrieved by the browser as JS. Only pay attetion on the kind of processing the PHP in the javascript file does: it may depend on the context you had in the main script, so additional adjustments may be necessary.
In short, you can't pass the PHP variables directly to an external JS file without some work in PHP generating the files, then sending custom headers to treat the file as JavaScript (edit: see post by Marcovecchio if this sounds like a likely solution)... a quick solution is to pass the variables inline so they are global, then use them inside your external file. This will allow for the majority of your JavaScript to be in external files, but also allow you to pass your variables from PHP to JS.
By no means is this the best solution, but it's more than likely the easiest to get working.
Here's an example:
<script type="text/javascript">
var grp_list = <?php echo json_encode($arr_grp); ?>;
var url = "<?php echo $_SERVER['PHP_SELF']; ?>";
</script>
<script type="text/javascript" src="external.js"></script>
During a site scraping, I discovered several scraped functions in JavaScript that I need to modify because the code uses a relative path:
/UserControl/bla
I need to modify it to use absolute path:
www.domain-name.com/UserControl/bla
The problem is, those functions written in a separate file included by the scraped page. So far I can only stream that file using the PHP function file_get_contents(), change the part I need using preg_replace, and insert that script in the head section of the scraped HTML. I don't have access to modify the included JavaScript file because it's on a server I don't have access to.
Is that the right way to do this?
What I do in this cases is to declare JavaScript global variables with the objective to be constant values, then, I can access this variables from my included JS files, for example:
<script>
Globals = {
absoluteUrlPrefix: "<?= getAbsoluteUrlPrefix(); ?>"
};
</script>
<script src="myjsfile.js"></script>
on myjsfile.js
...
var absoluteUrl = Globals.absoluteUrlPrefix+"/UserControl/bla";
...
preg_replace is an option, if it's just to show the web pages on your machine, you could also insert a base-path tag:
http://www.w3schools.com/tags/tag_base.asp
I've been developing my site with the site directory structure as
www
img
javascript
include
index.php
Now I want to change it to
www
index.php
dir1
dir2
...
themes
theme1
img
javascript
include
index.php
At the theme level index.php, earlier I've my paths to javscript files as javascript/file1.js or so.
Now I've changed the paths to <?php echo THEME_PATH . "javascript/file1.js"?>
This includes the js files, however my problem is when I reached inside the js file.
For example, in one script.js file, I've a jquery method called as
$('#pop-con').html('<p><img src="img/ajax-loader.gif" width="220" height="19" /></p>');
I can't use php inside the js file. So how do I change the paths similar to the php implementation above??
Relative paths
Probably one of the easiest ways to solve it is using relative paths.
In your case you will need to be one directory up (../), so it would be:
$('#pop-con').html('<p><img src="../img/ajax-loader.gif" width="220" height="19" /></p>');
You can have a small <script> on your pages that creates a global variable to store the "THEME_PATH" value:
<script>
window['THEME_PATH'] = '<?php echo THEME_PATH?>';
</script>
Then your JavaScript files can just look for the global variable and use it to construct paths. I keep such code in a global template header that's used for all the pages in my application. There really are only a very small number of things like that to worry about; in my application I think there are like 4 or 5 items of information like that to communicate with included .js files.
Solution, in case anyone else need it.
I put the following code in my theme level index.php file
<script>
window.themePath = "<?php echo $site_info[theme_style_path]; ?>";
</script>
And use the javascript global variable to append the path.
The source of the Javascript is irrelevant for the purposes of HTML being embedded within the page. What matters is the location of the page the HTML is embedded within.
For instance, if you load a page from example.com/index.php, and some Javascript loaded from example.com/js/script.js inserts some HTML into the main page, then image path references are going to be relative to /, as that's where the page was loaded from, not from /js.
As for embedding PHP in JS, you're right - but you can have PHP emit a .js file trivially:
<?php
header('Content-type: text/javascript');
?>
var settings = <?php echo json_encode($SETTINGS_ARRAY); ?>;
would generate perfectly valid Javascript, even thought it came from a PHP file.