I would love to post some starting code in this question, but to be honest, I' stumped.
I'm looking for a way to use PHP within my .JS file.
I would like to be able to use real PHP functions inside my "stuff.js" and then be able to include it using:
<script type="text/javascript" src="whatever.js"></script>
Any thoughts? Thanks.
<script src="/YOUR_PHP_FILE_PATH/file.php"></script>
Also add header in php file
header(Content-Type: text/javascript);
You just have to write your JavaScript into a php file and then include it
<script type="text/javascript" src="whatever.php"></script>
I would recommend you keeping your JS functions in a .js file and the variable data that needs to be output dynamically could be output directly in the main php/html file:
<script type="text/javascript" language="JavaScript">
var a = "<?php echo addslashes($a); ?>";
// ...
</script>
Other possibility would be to tell your server to proccess *.js file with php but I wouldn't recommend that as it could cause some unexpected problems.
It's impossible but you can use PHP file as a JavaScript file talking in a short way. ;)
<script type="text/javascript" src="whatever.php"></script>
And in whatever.php:
<?php
echo "var text = 'test';";
?>
alert(text);
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 have a loading gif for the gallery on my website. In my js file I have this code to show the loader:
image: $("<img src='images/loading.gif'/>"),
Currently this the image isn't appearing because I haven't put the full image path. But instead of putting the full image path, I would prefer to do this:
<img src="<?php bloginfo('url');?>/images/loading.gif”>
But I can't work out how to make this php work in my js file. How do I go about doing it in the easiest way?
I prefer to..
1) In my header include (the php include that contains any <head> data), write a small
inline JS function that creates a global object containing any variables I need from the server (PHP). I can use the 'echo' and 'json_encode' functions here because its in an inline JS snippet in a php file.
2) You could write a JS function inside your JS file that uses AJAX to call a PHP file, which will return the same JSON encoded data as number 1, then you parse it and assign in to a global variable.
Both essentially do the same thing, except with 2 you are using AJAX, which will add an additional request. I prefer option 1, because it is done along with the pages execution. Option 2 may require you to wait until the DOM is ready, depending on various aspects of your program (in which I can not tell).
Option 1 requires inline JS, but you really shouldn't harp on this, as with dynamic websites it can actually be a plus, as along as it is short and concise. Some people get on others about inline JS. Don't let them yell at you.
I am not totally sure what you are trying to do. But if that JS isn't working, why not including a php file, or just writing some php in the header, that includes the JS inside it in 'echo()'. I.e:
echo('?><img src="<?php bloginfo('url');?>/images/loading.gif" /><?php');
Correct me if I am misunderstanding your intent.
You can't place PHP code directly into a .js file, but you could have some javascript in the head element of your PHP file right before including the javascript file.
In this javascript you could then define variables and assign data to them using PHP. These variables would then be accessible from inside the javascript file.
<head>
<script type='text/javascript'>
var _g_bloginfo = "<?php echo '...'; ?>";
</script>
<script type='text/javascript' src='javascript.js'></script>
</head>
A cleaner technique for passing PHP data to JavaScript is to store the data in data attributes which you can then access via JavaScript. As a simple example:
<body data-home-url="<?php echo home_url(); ?>">
You can access that in jQuery like:
var home = $('body').attr('data-home-url');
FYI you can use json_encode to convert PHP object/arrays into a JSON objects which you can read via $.parseJSON or JSON.parse. WP's wp_localize_script can actually do this for you, but note that in that case it'll expose the converted data to the window.
You can create a php file instead (of your js file with all the code you already have in that js file + references to your php variables/functions) and include that in your main php file.
Example html:
<?php $example = 23; ?>
<html>
<head><title></title>
<script type="text/javascript">
<?php include('js.php'); ?>
</script>
</head>
<body></body>
</html>
js.php:
var a = <?= $example ?>;
alert(a);
will eventually output:
<html>
<head><title></title>
<script type="text/javascript">
var a = 23;
alert(a);
</script>
</head>
<body></body>
</html>
I want use a jQuery plugin in category.tpl. Put files in javascript/jquery directory. Now, how can use this plugin?
/* one can load JS like that: */
if(file_exists('catalog/view/javascript/'.$this->config->get('config_template').'/script.js')) {
$this->document->addScript('catalog/view/javascript/'.$this->config->get('config_template').'/script.js');
}
It is rather "the proper way" to use existing functions, than to add scripts manually into header.tpl.
As a hint, based upon the answer below - one could loop an array of filenames, in order to keep control over the loading order, which is often relevant while they might depend on each other.
I've never used OpenCart, but a quick google session tells me that you should include the plugin scripts (just like any other js) in a file called header.tpl.
Here is a part of an sample header.tpl-file I found:
<script type="text/javascript" src="catalog/view/javascript/jquery/jquery-1.3.2.min.js"></script>
Just add a the following line below the jQuery include so it looks like this:
<script type="text/javascript" src="catalog/view/javascript/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="catalog/view/javascript/jquery/[PLUGIN FILE NAME].js"></script>
and you should be good to go.
First paste your jquery files, css files and images in catalog/view/javascript/yourplugin folder.
Then call the jquery plug in files in catalog/view/theme/yourtheme(default)/template/product/category.tpl file.
For ex,
YOur php code;..
...
....
<script src="catalog/view/javascript/jquery/jquery-ui-min.js"></script>
<script type="text/javascript" src="catalog/view/javascript/jquery/jquery.anythingslider.js"></script>
<link rel="stylesheet" href="catalog/view/theme/default/stylesheet/anythingslider.css">
<script>
// DOM Ready
$(function(){
$('#slider').anythingSlider();
$('#slider1').anythingSlider();
$('#slider2').anythingSlider();
});
</script>
its for slider.. you can do your action in php (above the script).
You'll need to include JS and CSS sources in Header View (/catalog/view/theme/[your theme]/template/common/header.tpl)
in config.php
define('DIR_JAVASCRIPT', 'D:\wamp\www\opencart/view/javascript/your_dir/');
in header.tpl
<?php
if (is_dir(DIR_JAVASCRIPT)):
if ($handle = opendir(DIR_JAVASCRIPT)):
while (false !== ($file = readdir($handle))):
if (preg_match('#\.js$#', $file)):
?>
<script type="text/javascript" src="<?php echo 'view/javascript/your_dir/'.$file; ?>"></script>
<?php
endif;
endwhile;
closedir($handle);
endif;
endif;
?>
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.
If you look at the source of this page http://kingston.talking-newspapers.co.uk/ you will see a large amount of inline javascript near the top.
I don't really want all this extra stuff floating around in my page source, I'd much rather get it off into a script tag, and then I can minify it and all sorts.
If I call it as a php file, this SHOULD work in theory, I just end the js file extension with php instead, and in the header I put the following:
header("Content-type:application/x-javascript");
but... a lot of the php variables used to generate the playlist within the javascript are setup at the beginning of the main index.php file, and in calling this php-generated js playlist file like this, it seems to evaluate it entirely separately, so it's full of errors.
The only way round it I can think of is to have the page write a file, then immediately read it in. The other thing is, the playlist is likely to change often and dynamically, so I think I need to get minify to NOT cache it?
I made the solution by following this tutorial, which redirects the generate inline script to a file, then immediately reads that file in.
http://my.opera.com/zomg/blog/2007/10/03/how-to-easily-redirect-php-output-to-a-file
So now my page looks like:
<?php
require("./filewriter.php");
$obfw = new OB_FileWriter('jplay_gen_playlist.js');
$obfw->start();
require($includesdir . "jplayerscript.php");
$obfw->end();
?>
<script type="text/javascript" src="jplay_gen_playlist.js"></script>
et voila! All nicely external, can be minified, cached etc.
You can do it in two ways. First would be set up the variable inline and then include the script:
<script type="text/javascript">
var myPlayList = [
{
name: "Introduction and guidance on usage",
mp3:"http://www.talking-newspapers.co.uk/find/soundfiles/TnHomePageIntro.mp3",
ogg:"http://www.talking-newspapers.co.uk/find/soundfiles/kingstonkt9.ogg"
}
...
</script>
<script type="text/javascript" src="myinclude.js"></script>
The other would be to have your included .js file a simple library of functions which you include at the top of the page and then call from some inline javascript:
<script type="text/javascript" src="myinclude.js"></script>
....
<script type="text/javascript">
$(function() {
var myPlayList = [ ... ];
startPlaylist(myPlayList);
});
</script>
I would personally choose the second method. You shouldn't need to generate any of the script dynamically (as far as I can see, it can all be hard-coded except for the playlist, right?) Any other things you need to pass to the script could still be passed in by your startPlaylist() method call anyway.