php arrays in external js file - php

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>

Related

Embedding PHP in Javascript doesn't work

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.

What is the best way to modify the JavaScript included in a scraped web page?

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

Inserting php into js file

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>

What are the side effects of parsing JS files as PHP?

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.

echo php variable on external javascript possible?

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.

Categories