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.
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>
What is the difference between following two ways of including a javascript file:
1. Including javascript file directly in the main php page, as:
In main.php : <script type="text/javascript" language="javascript" src="custom-script.js"></script>
versus
2. Including javascript file in a php subpage, which further is included in the main php page, as:
In main.php : <?php include('subpage.php'); ?>
and In subpage.php : <script type="text/javascript" language="javascript" src="custom-script.js"></script>
The only probable difference would be placement of the code which include the js file and hence the difference might be visible on final output HTML, if the functions are dependent in multiple js files.
Note: The placement of the code does matter in execution of the functions dependent on the js
It makes no difference in the end. Either way, the JS file is included by the client's browser.
This is not going to make any difference to the browser.
There is no difference, unless using the sub page makes the <script> tag appear further down the page, in which case the browser won't execute it until it reaches that point.
As far as the browser is concerned, everything is "one page", it is not aware of any includes or divisions across PHP scripts.
It makes no difference to the browser.
However for architecture style is better to have all JS inside separated php file that is included elsewhere.
This way you'll have much better control what you are including (one place control). If you want to add another script later on, you can just add it to subpage.php (better to name this something like javascript-includes-header.php) and you will have another script included on all pages. Same goes for removing a script or if you figure out that script include order is important.
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>
So since joining I've learned a lot - compared to where I was - but I still don't know the terminology and functions well enough I suppose... so here's my problem:
I'm making several js-based galleries. The idea being that there will be 3-4 pages containing some thumbnails that will populate a specific div with the corresponding art and copy (a div I'm calling using innerHTML) and so far that works. Here is the script:
function changeDiv(target,id) {
var target = document.getElementById('generic');
var id = document.getElementById(id);
target.innerHTML = id.innerHTML;
}
This works great... when I have the 'target' and all 'id's in the same page. I even went as far as using a php include on the page (I added it to the footer) and nested it inside an inline div that I set to visibility:hidden. A shot in the dark but this worked too. EXCEPT that my footer was now about another 100px taller with nothing but blank space. Apparently it HID the content, but made plenty of room for it.
But what I really want to do is include the source of the divs I'm calling (we'll call them artwork.php) into the gallery page ( ...and gallery1.php) the same way a css or js is linked in the header or the same way it is included with a php tag but without messing up any of my objects.
I hope that made sense, but in brief: How can I call an external php document that won't display but can be called upon by the js?
Any thoughts?
1) visibility:hidden; keeps the place on the page. Use display:none instead.
2) Jo have two possibilities.
a) Use Ajax (google it!) if your artwork.php will change dynamically.
b) Use artwork.php as JS file, ie like this:
<?php
/* artwork.php */
header('Content-type: application/javascript');
echo "var myImages = [{'name':'First image','src':'image1.jpg'},{'name':'Next image','src':'image2.png'}];\n";
?>
//... any other JS functions here ...
And gallery1.php:
<html>
<head>
<script type="text/javascript" src="artwork.php"> </script>
</head>
<body>
...
</body>
hmm i am not actually getting what u are trying to say but i think this might help
save your php page lets say "artwork.php"
then use the jquery Load to call the page and hide the div where you have loaded the page.
$("#any_div_u_want").load('artwork.php',function(){
$(this).hide();
});
now u can show the div which contains your php script wheneveer u ant with just
$("#any_div_u_want").show();
Hope this helps
I have some javascripts that I am using in my files. But when we view the source code it shows our javascript as it is. Is there any way with which we can hide our javascript from showing up in the browser using php.
There is a free javascript obfuscator at javascriptobfuscator.com. It will not prevent dedicated people from "stealing" your code, but normal copy&paste will not be easy.
Also see this question: How can I obfuscate (protect) JavaScript? . It contains some very good answers and also explain how this is security through obscurity.
That's how it works, it visible to everyone.
You can obfuscate it, though.
As Javascript is executed inside the browser, on the client's machine, it has to be sent to that client machine.
So, one way or another, the client has to be able to read it. So, no, you cannot prevent your users from seeing the JS code if they want to.
You could obfuscate it, but someone who really want to get to your source will always be able to (event if it's hard)... But the thing is : why would you prevent your users from seeing the JS source code if they want to ?
As a sidenote : with minified/obfuscated JS code, when you'll have a bug, it'll be really harder to track down... (and you really have to keep a no-obfuscated version on your development/testing machine)
I recommend minifying it and that will remove the comments and white spacing from your code. If you don't want the names of the variables visible then you will need to obfuscate it.
I'm not sure if this will work, I may try it sometime. But basically:
<script type="text/javascript" src="MyScript.php"></script>
In the PHP file add some sort of refering to check what page requested it or what the last page was. Then if it was one of your own pages, then echo the JS, if not then don't echo it. It will still be possible to read the JS, but even harder than just viewing source and de-obfuscate it. So you could also obfuscate the code inside the .php file.
no. javascript executes on the client side.
There is another way of hiding the Javascript for the most simple users
Just test here to try finding the javascript behind the textbox...
Yet, the script is still visible for experienced users -see the bottom of this post to understand why-
The idea is to put your javascript functions in a separate ".js" file. When loading your source PHP or HTML page, instead of calling it directly with
<SCRIPT language="JavaScript" SRC="original_file_to_hide.js"></SCRIPT>
, you will include a header php script that will copy the "mysource.js" file to a random "kcdslqkjfldsqkj.js" file, and modify your HTML file to call
<SCRIPT language="JavaScript" SRC="temporary_copy_of_the_file.js"></SCRIPT>
instead. After that, just delete the copy kcdslqkjfldsqkj.js file on your server, and when the user will look for the source code, the browser will link to a vanished file !!!
So this is for the theory, next, there is a small issue to workaround : if the HTML/PHP file is loaded too fast, your script will be vanished from your server before the browser had time to load the script.
Thus, you need
To copy the file to a different random name
To load the file in the source PHP file
To wait a few seconds after your HTML/PHP file is loaded before...
...Deleting the file
Here is the source for the HTML/PHP "test.php" page which is to be displayed to the end-user:
<?php
//javascript source code hiding technique : Philippe PUECH, 2013
//function thanks to Stackoverflow, slightly modified
//http://stackoverflow.com/questions/4356289/php-random-string-generator
function RandomString()
{
$characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
$randstring = '';
for ($i = 0; $i < 10; $i++)
{
$randstring = $randstring.$characters[rand(0, strlen($characters))];
}
return $randstring;
}
//simple header script to create a copy of your "precious" javascript ".js" file
$original_filename="functions.js"; //find a better (complicated) name for your file
$hidden_filename=RandomString().".js"; //temporary filename
copy($original_filename,$hidden_filename);
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Catch my Javascript if you can !</title>
</head>
<SCRIPT language="JavaScript" SRC="<?php echo($hidden_filename); ?>"></SCRIPT>
<script type="text/javascript">
</script>
<body onLoad="javascript:testfunc();">
This is the page with anything you like !
</body>
</html>
<?php
sleep(1);
//you can comment following line
echo "finished !";
unlink($hidden_filename);
?>
Here is the source for the "functions.js" file which will be hidden to the user.
// JavaScript Document
function testfunc(){
alert("It works...");
}
However, as told in the comment, the developer tools of the browser will keep the script in memory, and make it still visible to the curious users... ;-((