Can I reference an external JavaScript file in a PHP file? - php

I cannot seem to get this to work. I have a small JS file that switches banners depending on the time of day, but it seems that doing an external reference in my PHP file does not work. It works fine in an HTML page.
This is the code in the JavaScript file.
function getStylesheet() {
var currentTime = new Date().getHours();
if (7 <= currentTime && currentTime < 19) {
document.write("<img src='images/banner_day.jpg'>");
} else {
document.write("<img src='images/banner_night.jpg'>");
}
}
getStylesheet();
And here is the reference code I used to call the JavaScript file. Its in a PHP file.
<script src="http://beta.website.com/wp-content/themes/theme/scripts/banner.js"></script>
Everything on the PHP page shows up in the browser, except for the banner that I tried to call with the script.
Here is the entire PHP file code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div id="main">
<div class="container">
<div id="header">
<div id="logo">
<img src="http://beta.dfdfdf.com/wp-content/themes/asdafd/images/logo.png" />
</div>
<div id="shadow2"></div>
<div id="shadow1"></div>
<ul id="menu">
<li>df</li>
<li>df</li>
<li>fd df df</li>
<li>The asfdssd asdfds</li>
<li>sf</li>
<li>df</li>
<li>dfd</li>
</ul>
<div id="slogan"><big>"fasfdsads2005."</big></div>
<div id="loginDiv">Login Panel Here</div>
</div>
<div id="banner">
<script src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script></div>
<div class="sidebar">
Sidebar Content<br />
<br /><br />
blah
blah
blah
</div>
<div class="content">
Main Content
<br />
<br />
<br />
<br />
<br />
<br />
</div>
<div id="footer">
<div class="container">
<div class="footer_column long">
<h3>Cadsfadsfafdfsd.com All Rights Reserved</h3>
<p>dsafasdfdffadffadsdafsdfsadafsdfsadfas</p>
</div>
<div class="footer_column2">
<h3>More Links</h3>
<ul>
<li><a href="http://aadfsdfsdfa.
com">asfsdfa</a></li>
<li><a href="http://ItsNotch.
com">ItsNotch</a></li>
<li><a href="http://adfasfsfaf.
com">adsfasf</a></li>
<li><a href="http://twitter.
com/safs">Twitter</a></li>
<li><a href="https://www.facebook.com/group.php?gid=10215yy20340498">Facebook Fan Page
</a></li>
</ul>
</div>
<div class="footer_column2">
<h3>RSS</h3>
<ul>
<li>RSS Feed</li>
<li>What is RSS?</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>

Try changing your Javascript to this:
window.onload = function () {
// Uncomment this line to make sure the script is loading/running, then delete it
// alert('Hello, your Javascript is running');
// Declare variables
var currentTime, bannerDiv, newImg;
// Get currentTime
currentTime = new Date().getHours();
// Get 'banner' div
bannerDiv = document.getElementById('banner');
// Get create a new <img>
newImg = document.createElement('img');
// Assign a src="" attribute depending on the time
newImg.src = (currentTime > 7 && currentTime < 19) ? 'images/banner_day.jpg' : 'images/banner_night.jpg';
// add the new image to the document
bannerDiv.appendChild(newImg);
};
And put it in the <head> of the document, so change
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<!-- ....... -->
<div id="banner">
<script src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script>
</div>
<!-- ....... -->
...to:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js"></script>
</head>
<body>
<!-- ....... -->
<div id="banner"></div>
<!-- ....... -->
If it still doesn't work, one of two things is happening:
Your javascript file is not actually at http://beta.adsfasfasfd.com/wp-content/themes/adfadsf/scripts/banner.js so the script cannot be loaded/run. Uncomment the first line to confirm that the script is running.
Your banner images cannot be found at images/banner_night.jpg - make sure your relative paths are correct.

Have you made sure that you've actually got the <script></script> in your head? I certainly can't see it there (unless it is in <?php wp_head();>?).
Having attempted to navigate to http://beta.website.com/wp-content/themes/theme/scripts/banner.js it returns a 404, you'll need to fix this issue first.
Remember that javascript is client side, and all you want to do with php is spit out the tags somewhere for the browser to deal with.

It might be path problem.
What is you images (full) path?
What is you page (full) path?
As it is now it looks for images directory beneath your current page. Is this correct?

Related

Trying to create indicator of relay on website

I'm having trouble with creating some sort of indicator on a webpage.
This should show me if something is turned on or off.
My project concerns on making a "automatic" terrarium controller, with sensors, relays and a raspberry. I'm able to show the sensor readings on a website, updating every minute (using jQuery).
At certain times, some relays are activated (which still has to be done, relay arrived today) and I want to see on the site if relay 1 is activated or not and again, updated automatically when this changes. The program to activate some relays is in python, and will also write a txt-file, containing a "0" or a "1" (for "off" and "on").
Then, using for instance a switch (e.g. switch) which should show the state of the relay, according to the txt file.
But, I don't seem to get it working.
Using PHP If and Else statements, ends up showing both even when using simple images as "indicators" of the relay.
<?php
$myfile = fopen("./statusUV.txt", "r") or die("Unable to open file!");
$status= fread($myfile);
if ($status == 1){
print ('<img src=./images/on.png />');
}
else{
print ('<img src=./images/on.png />');
}
But, how can different div's been shown, in case of this switch?
Oh, and I have to say, I'm new to PHP, HTML, Python, jQuery etc.
The "button" doesn't have to be clickable, it just have to show the state of the relay (or the output in the file).
If more information is needed, please, let me know!
Thanks in advance!
<!DOCTYPE HTML>
<html>
<head>
<title>UV</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="description" content="" />
<meta name="keywords" content="" />
<link href='http://fonts.googleapis.com/css?family=Open+Sans+Condensed:300,700' rel='stylesheet' type='text/css'>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/skel.min.js"></script>
<script src="js/skel-panels.min.js"></script>
<script src="js/init.js"></script>
<noscript>
<link rel="stylesheet" href="css/skel-noscript.css" />
<link rel="stylesheet" href="css/style.css" />
<link rel="stylesheet" href="css/style-desktop.css" />
</noscript>
<?php
$myfile = fopen("./statusUV.txt", "r") or die("Unable to open file!");
$status= fread($myfile);
fclose($myfile);
switch(intval($status)){
case 0 : $img = "<img src='./images/off.png' />"; break;
default : $img = "<img src='./images/on.png' />";break;
}
?>
</head>
<body class="left-sidebar">
<!-- Wrapper -->
<div id="wrapper">
<!-- Header -->
<div id="header">
<div class="container">
<!-- Nav -->
<nav id="nav">
<ul>
<li class="active">Data</li>
<li>UV timer</li>
<li>Heat Timer</li>
<li>Led Timer</li>
<li>Sproeier Timer</li>
<li>Apparaten</li>
</ul>
</nav>
</div>
<div id="logo-wrapper">
<div class="container">
<!-- Logo -->
<div id="logo">
<h1>Timer<span class="tagline"> voor Sproeier</span></h1>
</div>
</div>
</div>
</div>
<!-- /Header -->
<!-- Main -->
<div id="main-wrapper">
<div class="divider"> </div>
<div id="main">
<div class="container">
<div class="row">
<div id="sidebar" class="4u">
<?php
if (isset($img)){
echo $img;
echo $status;
}?>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="divider"> </div>
<!-- /Wrapper -->
<div id="copyright">
<div class="container">
<p style="font-size:11px">Design: TEMPLATED Images: Unsplash (CC0)</p>
</div>
</div>
</body>
</html>
Assume the var $status = 1 or 0 in the text file.
Your code must be like that :
<html>
<head>
<?php
$myfile = fopen("./statusUV.txt", "r") or die("Unable to open file!");
$status = fread($myfile);
fclose($myfile);
switch(intval($status)){
case 1 : $img = "<img src='./images/on.png' />"; break;
default : $img = "<img src='./images/off.png' />"; break;
}
?>
</head>
<body>
<?php
if (isset($img)){
echo $img;
}?>
</body>
</html>
Some PHP-problems has been solved by reseting the server. Apparently that would fix the strange code appearing on the site.
Now, after testing various things, it appears that $status remains empty. After trying various techniques, I found that fgets($myfile) would do the trick, instead of the fread($myfile)! Thanks everyone for helping!

My audio file is not playing

I have a jplayer here to play an audio: AUDIO
Problem is that it is not playing my audio file I have. How can I get the audio to play?
The audio files comes from the directory AudioFiles/Kalimba.mp3. I retrieve the directory from the db and then tell the jsplayer to play the audio in this directory. This should have then played the audio but nothing happens if I click on the play button
jplayer summary here: http://www.jplayer.org/latest/quick-start-guide/step-8-audio/
Below is code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Preview Audio</title>
<link type="text/css" href="jquery/skin/jplayer.blue.monday.css" rel="stylesheet" />
<script type="text/javascript" src="jquery/jquery-1.7.min.js"></script>
<script type="text/javascript" src="jquery/jquery.jplayer.min.js"></script>
</head>
<body>
<?php
$getaudio = 'AudioFiles/' . $_GET['filename'];
$audioquery = "SELECT AudioFile FROM Audio WHERE (AudioFile = ?)";
if (!$audiostmt = $mysqli->prepare($audioquery)) {
// Handle errors with prepare operation here
}
// Bind parameter for statement
$audiostmt->bind_param("s", $getaudio);
// Execute the statement
$audiostmt->execute();
if ($audiostmt->errno)
{
// Handle query error here
}
$audiostmt->bind_result($dbAudioFile);
$audiostmt->fetch();
$audiostmt->close();
?>
<script type="text/javascript">
$(document).ready(function(){
$("#jquery_jplayer_1").jPlayer({
ready: function () {
$(this).jPlayer("setMedia", {
mp4: "<?php echo $dbAudioFile; ?>"
});
},
swfPath: "/jquery",
supplied: "mp3"
});
});
</script>
<?php echo "File Path " . $dbAudioFile; ?>
<div id="jquery_jplayer_1" class="jp-jplayer"></div>
<div id="jp_container_1" class="jp-audio">
<div class="jp-type-single">
<div class="jp-gui jp-interface">
<ul class="jp-controls">
<li>play</li>
<li>pause</li>
<li>stop</li>
<li>mute</li>
<li>unmute</li>
<li>max volume</li>
</ul>
<div class="jp-progress">
<div class="jp-seek-bar">
<div class="jp-play-bar"></div>
</div>
</div>
<div class="jp-volume-bar">
<div class="jp-volume-bar-value"></div>
</div>
<div class="jp-time-holder">
<div class="jp-current-time"></div>
<div class="jp-duration"></div>
<ul class="jp-toggles">
<li>repeat</li>
<li>repeat off</li>
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
debug it with console, ex. firebug (ff plugin) and paste the result here please

PHP JSON object will render on local host but not from remote server

I am creating a really simple mobile app for our local track club. The app seems to be working fine when I test it on my localhost but when I change the links to point to my remote server and then package the app nothing seems to render. I am hoping that this is a really easy fix. Here is a page that I would like to populate using a JSON object into a HTML frame using Javascript.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>United Track Club</title>
<link href="jquery-mobile/jquery.mobile-1.0.1.min.css" rel="stylesheet" type="text/css"/>
<!-- This reference to phonegap.js will allow for code hints as long as the current site has been configured as a mobile application. -->
<script src="jquery-mobile/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="/phonegap.js" type="text/javascript"></script>
<script src="jquery-mobile/jquery.mobile-1.0.1.min.js" type="text/javascript"></script>
<!--a name="viewport"content="width=device-width, initial-scale=1"> -->
</head>
<body>
<div data-role="page" id="runnerListPage">
<div data-role="header">
<h1>Runners2</h1></div>
<div data-role="content">
<ul id="runnerList" data-role="listview" data-filter="true">
</ul>
</div>
<div data-role="footer" data-position="fixed">
<div data-role="navbar">
<ul>
<li>Home</li>
<li>Search</li>
<li>Schedule</li>
</ul>
</div>
</div>
</div>
</body>
</html>
Here is the JS that I created to populate the above code.
$.getJSON('http://unitedtrack.org/Mobile/TF/getrunnerlist.php', function(data){
var object = data.items,
runnerCount = object.length,
target = document.getElementById('runnerList'),
i;
if (runnerCount>0){
for (i =0 ; i< runnerCount; i=i+1){
var unitrun=object[i],
EventDt = unitrun.First_Nm,
MeetNm = unitrun.Last_Nm;
target.innerHTML +='<li>'+ EventDt +', ' +MeetNm +' </li>';
}
}
else {
alert('there are no runners');
}
});
target.addEventListener("click",data,false);
Thank you in advance for your help.
You need to set proper headers on the page you are querying (e.g. http://unitedtrack.org/Mobile/TF/getrunnerlist.php).
You need to set Access-Control-Allow-Origin header. See the link for more informations about cross-origin requests.

Why would javascript not work when the page is fully rendered but works when I get fatal PHP errors?

I've been attempting to use jquery and jqueryui to make tabs on my website. However, I can't seem to get them to work. The main page is in PHP, and I am using the Codeigniter framework. If the page fully renders, then the tabs won't work. If I change something that creates a fatal error in the php the tabs appear. While I was attempting to figure out what was going on I created a very basic page with only the jquery demo script, and it wouldn't work either. If it makes any difference, I am hosting on HostGator.
Please advise.
Header:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Sign Up!</title>
<link rel="stylesheet" href="<?php echo base_url();?>css/style.css" type="text/css" media="screen" />
<link rel="stylesheet" href="<?php echo base_url();?>css/jquery-ui-1.8.11.custom.css" type="text/css" media="screen" />
<!-- Java includes -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.11/jquery-ui.min.js" type="text/javascript"></script>
</head>
<body>
<div class = "header">
<span class="nav_bar"><?php if($this->session->userdata('is_logged_in')){ echo 'Welcome, ' . ucfirst($this->session->userdata('first_name')). " " . ucfirst($this->session->userdata('last_name')) . ' | ' . anchor('site/logout' , 'Logout');} else { echo anchor('site/is_logged_in', 'Login');} ?></span>
</div>
<div class="content">
Body:
<!-- Tab Script -->
<script>
$(function() {
$( "#tabs" ).tabs();
});
</script>
<!-- end Tab Script -->
<div id="tabs">
<ul>
<li>All Contacts</li>
<li>Place Holder Tab</li>
</ul>
<div id="tabs-1">
<?php $this->load->view('all_contacts_tab_view'); ?>
</div>
<div id="tabs-2">
Place Holder tab
</div>
</div>
Footer:
</div> <!-- end content div -->
<div class="footer">
<div class="footer_left">
<div id="copyright"> © 2011 NetworkIgniter. All rights reserved. NetworkIgniter, networkigniter.com and the all designs are trademarks of NetworkIgniter. Created with CodeIgniter and hosted on HostGator.</div>
<div id="legal">Terms and Conditions | Privacy Policy</div>
<div id="benchmarking">{elapsed_time} | {memory_usage}</div>
</div>
</div>
</body>
</html>
I did track down a java error after all, but I'm not sure how to fix it.
Error: $("#tabs").tabs is not a function
Line: 23
it looks like your calling tabs before it generated I would put that in doc ready
$(document).ready(function() {
$( "#tabs" ).tabs();
});
Figured it out.
It was the Google tracking script at the end. It was claiming the $. the reason why it was working when php crashed was because it wasn't getting down to the footer where the Google script was.
Errors on tabs are often due to a missing end of tag such as a </div> or </li> or whatever. Check the code generated by the PHP script to see if everything's fine. You might wanna use the Developper Tools Plugin on FireFox to detect any validation problems (including the missing tags).

How could I improve this template system?

At the moment, I have a base HTML template file. When ever I want to make a new page, I copy the template and place some require_once statements in between specific tags. I was wondering if there's a better way that would make it unnecessary to copy the template each time. Here's a typical example:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/second.css" />
<script language="JavaScript" type="text/javascript"
src="js/validation_functions.js"></script>
<title>Order a Ticket for the ball</title>
</head>
<body>
<div id="banner">St. Tom's Ambulance Ball</div>
<!-- START[container] -->
<!-- "body" -->
<div id="container">
<!-- START[header] -->
<div id="header">
<!-- header -->
<div id="header_text">introduction</div>
<div id="header_cell2">the process</div>
<div id="header_cell3">start</div>
</div>
<!-- END[header -->
<!-- START[content] -->
<!-- "other container" -->
<div id="content">
<!-- START[form] -->
<div id="form">
<?php
require_once(realpath($config["directories"]["views"]."/index.form.view.php"));
?>
</div>
<!-- END[form] -->
<!-- START[data] -->
<!-- "main content" -->
<div id="data">
<?php
require_once(realpath($config["directories"]["views"]."/index.data.view.php"));
?>
</div>
<!-- END[data] -->
<!-- START[side] -->
<div id="side">
<?php
require_once(realpath($config["directories"]["views"]."/index.side.view.php"));
?>
</div>
<!-- END[side] -->
</div>
<!-- END[content] -->
<!-- START[footer] -->
<div id="footer">
<!-- footer -->
<div id="footer_text">
<ul>
<li>home</li>
<li>partners</li>
<li>projects</li>
<li>contact us</li>
</ul>
</div>
<div id="footer_cell2"> </div>
<div id="footer_cell3"> </div>
</div>
<!-- END[footer] -->
</div>
<!-- END[container] -->
</body>
</html>
EDIT: I have taken note of your suggestions to use GET. The new idea is to have each request url formed as index.php?page=page_name. This request would then be dealt with by a main controller which then sets the variables of the template based on the value of $_GET['page']. For this, the template will now be:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="css/second.css" />
<script language="JavaScript" type="text/javascript"
src="js/validation_functions.js"></script>
<title><?php h($title) ?></title>
</head>
<body>
<div id="banner">St. Tom's Ambulance Ball</div>
<!-- START[container] -->
<!-- "body" -->
<div id="container">
<!-- START[header] -->
<div id="header">
<!-- header -->
<div id="header_text"><?php h($header_1) ?></div>
<div id="header_cell2"><?php h($header_2) ?></div>
<div id="header_cell3"><?php h($header_3) ?></div>
</div>
<!-- END[header -->
<!-- START[content] -->
<!-- "other container" -->
<div id="content">
<!-- START[form] -->
<div id="form">
<?php
require_once(realpath($view_1));
?>
</div>
<!-- END[form] -->
<!-- START[data] -->
<!-- "main content" -->
<div id="data">
<?php
require_once(realpath($view_2));
?>
</div>
<!-- END[data] -->
<!-- START[side] -->
<div id="side">
<?php
require_once(realpath($view_3));
?>
</div>
<!-- END[side] -->
</div>
<!-- END[content] -->
<!-- START[footer] -->
<div id="footer">
<!-- footer -->
<div id="footer_text">
<ul>
<li>home</li>
<li>partners</li>
<li>projects</li>
<li>contact us</li>
</ul>
</div>
<div id="footer_cell2"> </div>
<div id="footer_cell3"> </div>
</div>
<!-- END[footer] -->
</div>
<!-- END[container] -->
</body>
</html>
Note: h() is a function that first of all removes all undesired entity tags before echoing a string.
On a related note, at the top of each page I have some controller files which are included with require_once. I was wondering if it would be possible to implement a function that simply includes files based on a specific input string (name of the functionality/page) i.e "index" in this way:
function include_controller($page){
switch($page){
case "index":
require_once(realpath($config["directories"]["controllers"]."/index_.php"));
break;
case "checkout":
require_once(realpath($config["directories"]["controllers"]."/checkout_.php"));
break;
default:
break;
}
}
Instead of hard coding the includes into each file, you could have a controller file in which you pass the page to be displayed through a $_GET variable. The controller then handles the logic and includes the appropriate page or pages. This is the way a lot of MVC frameworks do it.
Edit: To answer your second question, instead of using a switch, you could just check to make sure the file exists. If it does, include that file, otherwise output an error ("Page doesn't exists" or something similar).
function include_controller($page){
if (file_exists($config["directories"]["controllers"]."/$page_.php")) {
// page exists, include it
require_once($config["directories"]["controllers"]."/$page_.php"));
} else {
// page not found
}
}
Obviously you should probably make the function a little more robust and probably limit the files that will be included to a certain directory or something. Also make sure you properly filter the $page variable so users aren't able to access any file.
Keep this one file as your template file. Then for all the functionality in your site always hit this file. Lets sat this file is index.php. So all functionality requests go to index.php. But with different parameters so for functionality A.
index.php?function=a
For functionality b
index.php?function=b
you can add more parameters also.
Now on the basis of a,b and the set of parameters see what files you want to include as require once.
Like the others already said, it would be better to use some kind of MVC framework. Or at least use a template engine (e.g. Smarty). Your example is ok though, for the 90ies :)
You can get by with one template if you choose a different way of specifying what page is being requested, such as using a GET variable. You can load the pages in a database and specify each of the included pieces, then have one php 'template engine' that loads the requested page from the database and outputs the template with the right includes.
If your server supports it, you can references to things you want to include on all pages in .htaccess:
php_value auto_prepend_file "header.php"
php_value auto_append_file "footer.php"
(Found this on codingforums.com)

Categories