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>
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>
Currently i'm working on a project which requires dynamical content parsed using some simple javascript functions, which i need to load depending on which 'view' is currently using a given user.
I'm having issues using something like this on a .js or .php file:
** .php file that calls javascript.
<script type="text/javascript" src="*.js/.php" />
** .js file
<?php header(Content-type: 'application/javascript'); ?>
alert('this shows correctly);
<?php if(isset($_REQUEST['view']) {
if($_REQUEST['view']=='private_view') { ?>
var xname = <?php echo $_SESSION['x']; ?>
//Array stuff filled from MySQL queries.
<?php } ?>
<?php if($_REQUEST['view']=='public_view') { ?>
var other_variable = <?php echo $xxx; ?>
$(element).functions();
<?php } ?>
The php code i'm using works correctly, already tested it. I'm also convinced that there are other ways to work this around, like using different files and choosing them with a conditional right on .php where I define script call, but i'm so curious about why this isn't working.
I'm used to work like this wrapping HTML content between brackets, to hide or show depending on given conditions.
The output of this will be only alert call, no PHP error/warning/notification,
I can't seem to find a correct way to do this, have been searching for a while but only find how to parse .js as php modifying .htaccess file.
You should simply rename the .js file to a .php file.
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 want to create tabs according to data from MySQL database using php for instance count the number of groups if they are 5 create 5 tabs.How could i do that.
You can generate JS from PHP just as easy as HTML.
If you are using inline JavaScript within your PHP file, you can just open up PHP and print out whatever you need.
<script type='text/javascript'>
var foo = <?php echo $bar; ?>;
// this will create "var foo = 4;" if $bar = 4
</script>
If you are using .js files, you can tell your HTTP server to pass .js files through PHP with this change in Apache for example.
AddType application/x-httpd-php .php .js
Now Apache will pass .js files through PHP first. This can increase load on the server, and .js files are often cached more than php or html files.
You could use the jQuery Tabs widget.
Each tab is made up of a list item and a div element, and it should be easy to write those from the content of your db in PHP.