Pass a php variable to a dynamic php'd external js file - php

I have a php file as my main page, and I want to pass a php variable to an external js file that is drawn with php. I have several php'd external js files that work fine but are "not" dependent on php from the main page. Some are dependent on JavaScript from the main page, but I want to move away from that. My intentions are to keep the main page clean by limiting the amount of JavaScript on it, by increasing dynamics, and to allow better site management.
Maybe if I understood the natural relationship of external files to the calling page, i dun know. For instance, the code below is some of my current code, and it assumes the external js script, being the php file it is, sees "functions.php" and $sel_entity from the main page. However, it does not seem to work that way. I am guessing maybe functions.php needs to be included in the external file, but no clue with $sel_entity. I am aware I could echo variables to a js variable on the main page, but I need something more dynamic for my plans. Any help here would be great. Thank you!
For instance, the main page is something like:
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php $sel_entity = $_GET['entity']; ?>
...//bunches of code
<script type="text/javascript" src="javascripts/lines.php"></script>
Then the js file lines.php is something like:
<?php
Header("content-type: application/x-javascript");
$job_set = get_jobs($_GET['entity']);
while ($job = mysql_fetch_array($job_set)) {
echo "
var jobLine";
echo $job["Project_ID"];
echo " = [new google.maps.LatLng(lati, longi),
";
$jobIdCoords = get_jobCoord_by_id($job["Project_ID"]);
echo " new google.maps.LatLng(";
echo $jobIdCoords['lat'] . ", ";
echo $jobIdCoords['long'] . ")]; ";
}
...// bunches more code
?>

The best way would be to use $_SESSION, but be sure to start the session in the "js" file.
<?php
session_start();
$_SESSION["foo"] = "bar";
?>
<script type="text/javascript" src="javascripts/lines.php"></script>
And then the JS file:
<?php
Header("content-type: application/x-javascript");
session_start();
echo 'var foo = "'.$_SESSION["foo"].'";';
?>
alert(foo);
However, you should be able to also use $_GET like so:
<script type="text/javascript" src="javascripts/lines.php?foo=bar"></script>
And the "JS" file:
<?php
Header("content-type: application/x-javascript");
echo 'var foo = "'.$_GET["foo"].'";';
?>
alert(foo);

Related

Php include not executed

I'm learning Php
And i made a main index.php page
And at some point it contains the line
<?php
include './BaseTemplate.php';
?>
BaseTemplate.php contains a lot of common plain html that is equal between all pages.
It looks like (but these are only a few lines) :
echo '<script src = "../assets/js/intention.js"></script>';
echo '<script src = "../assets/js/context.js"></script>';
echo '<head><body>';
echo '<table>';
But these echo commands dont get executed how should i resolve this ?
When you are including any file into your page the code for that file will come into the page.
So if the included file and the page where you are including it are in not in same path will create a problem.
It seems that you are getting that only. So please make the path in BaseTemplate.php according to the index.php, and it will work.
I solved it. I was thinking that include would put all code in a page from an external php source file. That's not the case, include files are libraries with functions which can be called.
So to resolve it, I rewrote it the BaseTemplate.php like this
<?php
Function WritePageBase() { // now i put it all inside a callable function
echo '<script src = "../assets/js/intention.js"></script>';
echo '<script src = "../assets/js/context.js"></script>';
echo '<head><body>';
echo '<table>';
}
?>
Now my other pages can call it like
<?php
include './BaseTemplate.php'; // include the file with functions
WritePageBase(); // call the function to echo all html code in page
?>
which reduces a lot of html code which now can be edited by a single file (and all other pages using it will change too).

PHP - How to include php script without it running before including

In my file index.php I have included this text from another file.
<title>
<?php
$title = "";
if (basename(__FILE__, ".php") == "index") {
$title = "Home";
} else {
$title = ucfirst(basename(__FILE__, ".php"));
}
echo $title;
?>
</title>
And I guess you can see what i does, and if not, then it's supposed to set the title to the basename of the file. So say you have a file called downloads.php, then the title with this script would be Downloads. But I have this problem which I don't know how to get past. When I include the text via.
<head>
include "filename.php";
</head>
And my problems is when I include the text, the 'script' runs before it includes. Say if the name of the file you included is filename.php and the main page where you have included the text is main.php, the header would be Filename and not Main. And the reason why I want to include the text, and not just paste directly into main.php is because it's much easier to edit if you have multiple files where you need the exact same code.
I hope you understand what I'm asking, and that you are able to help me.
Try $_SERVER['SCRIPT_NAME']:
if (basename($_SERVER['SCRIPT_NAME'], ".php") == "index") {
$title = "Home";
} else {
$title = ucfirst(basename($_SERVER['SCRIPT_NAME'], ".php"));
}
It looks like you're trying to set up a simple system for breaking your pages up into "subpages". Good idea. But rather than relying on the filename, why don't you set a variable? For example:
In page_title.php:
<?php
echo "<title>" . $title . "</title>";
In index.php:
<?php $title = "Home"; ?>
<head>
<?php include "page_title.php"; ?>
</head>
In some_other_page.php:
<?php $title = "Some Other Page"; ?>
<head>
<?php include "page_title.php"; ?>
</head>
And the same for any other pages you want...
In fact, you probably want to encapsulate the whole <head></head> section of your page.
Finally, rather than reinventing the wheel, you might want to look at some of the templating engines out there for PHP. I like Smarty, but there are others. These templating engines make it possible to write template files (including other template if necessary) and make it easy to simply pass variables to the template & render your HTML.

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.

Loading javascript in Code Igniter

For our Code Igniter application we are loading all of our javascript just before the closing body tag.
so in our controllers we have
$this->load->view('head', $this->head);
$this->load->view('main_view_for_controller', $data);
$this->load->view('foot', $this->foot);
And in the foot view we have a bunch of <script src="master.js"></script> tags.
These include
jQuery
jQuery-ui
shared-functions
Now this works great, until you think about JS used only on specific pages, or inline js.
You can't just dump your javascript anywhere in the page as it will generally use bit's and pieces of the parts you load at the bottom.
So what I do at the moment is,
I have /application/views/js/ where I will have something like login.php
login.php may contain e.g.
<script>
$(function(){
var user_id = <?php echo $this->user->get('id'); ?>;
var return = '<?php echo $return_url; ?>';
$('#login form').submit(function(){[...]});
$('#login .facebook').click(function(){[...]});
});
</script>
so in my controller I would call
$this->foot['js'][] = javascript('login', array('return_url' => '/users'));
//source of function javascript() from inside a helper
function javascript($file, $config = array()){
return $this->load->view('js/'.$file, $config, true);
}
then in my foot view after all the other files (which on the prod env are merged into one file and then minified) I have
foreach($js as $jsOut) echo $jsOut;
which simply spits out all the javascript.
Is this the best way of doing this? or is there a better way?
This just seems kind of messy...
A good idea might be to use page segments to determine what scripts to include. Rather than having to populate an array all of the time, you could define your scripts and what pages they belong too, then just check the page segments to determine what JS scripts to include. Read the documentation for the URI class here.
So in your include you'd do something like this.
<?php if ( $this->$this->uri->rsegment(2) == 'login' ): ?>
// Your login page specific scripts here
<?php endif; ?>
<?php if ( $this->$this->uri->rsegment(2) == 'home' ): ?>
// Your homepage specific scripts here
<?php endif; ?>
Replace the number 2's with whatever segment relates to the page you're on.

Passing parameter while including PHP script

I want to do this, but it gives error :( for better understanding my problem I'm giving an example:
<?php
include 'script.php?text=hiii';
?>
content of the script.php
<?php
echo $_GET['text'];
?>
So, how can i pass an argument while including the script page?
You could set $_GET['text'] before including the file:
$_GET['text'] = 'hiii';
include 'script.php';
But this obviously won’t affect other variables like $_SERVER['REQUEST_URI'], $_SERVER['QUERY_STRING'] etc.
After you include any script, the included script will act as it's in the same page.
For yourpage.php?text=hiii, that include('script.php') will automatically print hiii, as content of script.php will be in your included page.
You could've done something like this:
<?php
$_GET['text'] = 'what you want to do';
include('script.php');
?>
Actually we don't need to add it to $_GET. just create a variable and use it. Example:
script.php
<title><?php $text; ?></title>
<!--- other code goes here -->
index.php
<?php
$text = 'Welcome back';
include 'script.php';
?>

Categories