Is there a way to serve or add a js file to the code php/html pages when the site is loaded. I have 500+ pages and I am looking for a way to add a small snippet of code to all the pages.
e.g. onload www.xyz.com
- add javascript file/snippet to that page on runtime
The idea is to add a javascript snippet on the page loaded so it wont be server side it has to be client side.
And the code provided below still needs me to add the checking script on each page.
I need to know if there is a way to serve the file thru apache on site load ?
Assuming you have static pages with <html><head></head><body>whatever</body></html> kind of stuff. The following should work and be a quick fix. My method modifies the bottom closing </body> tag but you can modify it to alter the <head> or opening <body> tag
.htaccess
<IfModule php5_module>
php_value auto_prepend_file /var/www/vhosts/example.com/httpdocs/auto_prepend.php
php_value auto_append_file /var/www/vhosts/example.com/httpdocs/auto_append.php
</IfModule>
auto_prepend.php
<?php
ob_start();
?>
auto_append.php
<?php
$output = ob_get_clean();
$script = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/script.inc');
$output = str_replace('</body>', $script.PHP_EOL.'</body>', $output);
echo $output;
?>
script.inc
<script>
// using jquery method to attach onload:
jQuery(function(){
// do your js stuff here or load your external js, like with jQuery.getScript() or jQuery.ajax()
// http://api.jquery.com/jQuery.getScript/
// http://api.jquery.com/category/ajax/
});
// or if you want go without a framework and attach your onload event.
// in the most cross browser way see:
// http://stackoverflow.com/questions/1235985/attach-a-body-onload-event-with-js
</script>
yes you can.
Look how they loaded jquery dynamically:
Loading jQuery on-the-fly
a typical use case: jqueryfy
http://www.learningjquery.com/2009/04/better-stronger-safer-jquerify-bookmarklet
You may call a function, that calls script in body onload attribute
<body onload="addScript()">
<script type="text/javascript">
function addScript()
{
document.write("<script src='path\/to\/script.js' type=\"text/javascript\"><\/script>");
}
</script>
Use the Anthony Hatzopoulos solution, above.
ob_start();
in prepend and in append(via htaccess or php.ini) use:
<?php
$output = ob_get_clean();
$yourcode = "<yourscript/></body>";
$output = str_replace('</body>', $yourcode, $output);
echo $output;
?>
This is the best solution for me.
Related
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>
I need to be able to insert some PHP into an external .js file. Is this possible? I have created a slider using basic slider and need to have the page titles as markers at the top of the slider.
This is the code the .js file uses to generate the markers currently.
var slidenum = key + 1,
var marker = $('<li>'+ slidenum +'</li>');
I need to replace '+ slidenum +' with the WordPress function 'get_title'. Can this be replaced with php?
You can define JS variables in your php files, then use those variables in your external js.
for example, in one of your PHP files, you can add:
<script type="text/javascript">
// variable1 = number
variable1 = <?php echo $var1; ?>;
// variable2 = string
variable2 = "<?php echo $var2; ?>";
</script>
And for your question:
<script type="text/javascript">
slidenum = "<?php the_title(); ?>";
</script>
the_title() reference: http://codex.wordpress.org/Function_Reference/the_title
Update - The Loop:
<?php
$slider_titles = array();
if ( have_posts() ) : while ( have_posts() ) : the_post();
// your codes go here
$slider_titles[] = get_the_title(); // adds the title to the array
endwhile; endif;
?>
<script type="text/javascript">
slidenum = <?php echo json_encode($slider_titles); ?>;
</script>
When your loop is over then you add the javascript part
Some people are trying to tell you to use Ajax for this. That isn't the solution in this case. The variable is static for the lifetime of the page load, so there's need to keep going back to the server to get the value.
Others are suggesting setting the server to parse JS files as PHP so that you can embed PHP code into them. This also isn't a good answer, because you will lose all the browser's ability to cache the JS file, which will slow down your site and increase your bandwidth costs.
The solution is simply to add a separate single chunk of JS code to your page header -- ie add a small <script> tag to your page template, setting the variable in question.
The variable will then be accessible as a global in any JS code your run elsewhere in the page.
Yes, you can replace slidenum with get_title.
No, you cannot do this with javascript nor at runtime. You'll need to use AJAX for that.
Not directly. You can jump through a few hoops to get it done.
Problem is that .js doesn't get interpreted by PHP at all.
So if you must, you can use mod_rewrite and the like to pretend your php script is actually an .js.
Or write the js file from PHP completely to filesystem.
Or use XHR (Ajax) to fetch a certain value.
Another solution, not the best IMHO, is tell Apache to parse js files as php files. Simply put this in your .htaccess file:
AddType application/x-httpd-php .js
AddHandler x-httpd-php5 .js
<FilesMatch "\.(js|php)$">
SetHandler application/x-httpd-php
</FilesMatch>
I have some php variables that need to be used in javascript. Instead of passing vars back and forth using ajax, I chose to parse js files as php. Here's a simple example of what I did:
#.htaccess
AddType application/x-httpd-php .js
//scripts.js
//or for security reason, I could just use scripts.php and add header at the top)
header("Content-type: text/javascript");
alert("Hello <?php echo $_SESSION['username']; ?>");
I'v been using this method for a while, and I haven't noticed any obvious problems.
Are there any side effects doing things this way? Thanks.
I can't see any problem with this, but an easier solution for me was:
<script type="text/javascript">
var username = "<?=$_SESSION["username"]?>";
</script>
in the head-Zone of the template or index.
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.
I (absolute php beginner) was given a script with different variables that are based on date and time on the top of xhtml strict page:
<?php
$var1="2011,9,31,18,0,0";
[...]
?>
Inside the html body I have a javascript that currently starts like this:
<script type="text"/javascript">
dateFuture = new Date(<?php echo $var1; ?>);
[...]
</script>
Is it possible to make the javascript external, but still pull the variable $var1 from the top of the index page and then have it show the same output on the index page as it currently does?
I have found one example where the beginning of the external .js is supposed to look like this:
dateFuture = new Date(<?php include("/index.html");echo $var1;?>);
Unfortunately that doesn't seem to work.
Is there any possible solution for this?
Any help is greatly appreciated.
Thank you in advance.
Yes. Make the javascript variable global and you can access it inside you external js file.
Something like this
<script type="text/javascript">
var dateFuture = new Date(<?php echo $var1; ?>);
</script>
<script src="your-external-js-file.js" type="text/javascript"></script>
In your-external-js-file.js, you can access the dateFuture.
Or you can encapsulate the code in external js file in a class and pass on the date from php as a parameter to the constructor of that class.
The external JavaScript file itself can point to a PHP file — provided that the PHP file outputs valid JavaScript. That way, you can do something like the following:
myJS.php:
<?php
// Initialize your PHP variable(s) here, or include the PHP script(s) to do so.
$var1="2011,9,31,18,0,0";
...
?>
dateFuture = new Date(<?php echo $var1; ?>);
In your HTML file:
<script type="text/javascript" src="myJS.php"></script>
Since the output of myJS.php is purely JavaScript code, the file extension will not matter to the browser. Same way as your PHP code currently outputs purely HTML code, and your browser understands how to parse that as well.
If your purpose is to move the javascript code to an external script for better modularization, you can move it to a php file and then reference php file as javascript.
<script type="text/javascript" src="myscript.php"></script>
Inside myscript.php -
<?
Header("content-type: text/javascript");
dateFuture = new Date(<?php echo $var1; ?>);
?>
Whilst the answers given by Jonathan Newmuis and RonakG are perfectly acceptable and will work, the purpose of this answer is to answer your question as close to the setup you've got now as possible. However I'd personally agree with RonakG's answer.
If you're using Apache on your server then add the following line to your .htaccess file: AddType application/x-httpd-php .js. Alternatively you could add that code into the Apache configuration if performance is an concern for you.
The goal of that code is, essentially, to say that PHP should parse all files ending in ".js" as if they were ".php"
Yes. It is possible. However, you are going to have to make the javascript file into a php file, or force Apache, or whatever web server you use, to run javascript as php (perfectly harmless, because all code outside of <?php ... ?> is just written to output).
In my-external-js.php or my-external-js.js (whichever you choose, though I would recommend the former, because it requires less configuration):
<?php require_once 'file-which-defines-var1.php'; ?>
dateFuture = new Date("<?php print $var1; ?>");
Note: you should always use require_once instead of include or require, so that the same file is never included twice, which leads to messed-up variables and colliding functions/classes. Also, require and require_once case Fatal errors if the script could not be loaded, while include and include_once do not.