I am attempting to display the result of the PHP script on my webpage. To make sure that it actually works and recieves the data. Currently this isn't working. I have code in 3 seperate files that is supposed to handle this.
index.html
<div id="infoBoks">
<section>
<h1> Informasjon </h1>
<p id="parkInfo">test</p>
</section>
<section>
<h1> Innstillinger </h1>
</section>
</div>
script/javascript.js
var source = new EventSource("script/hent-status.php");
source.onmessage = function(e) {
document.getElementById('parkInfo').innerHTML += e.data + "<br>";
};
The PHP file has 3 different outputs: time, frequency and data. The data variable is a hardcoded array that is a part of a function that grabs a randomized index from the array. data[random] is then what is supposed to be returned with the script. The data is also supposed to be refreshed after a certain time, decided by the frequency variable. The PHP file is provided as a part of the project I'm currently working on. Currently I'm unsure where to proceed from this, seeing as i would expect this code to work based on the theory material I've been through.
*Note: The PHP file is also placed within the script folder.
*Note: Yes, there is a reference to the javascript file within index.html. There is also other code in the .js file that works fine with the .html file.
Edit* included hent-status.php
<?php
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
function sendMelding($id, $beskjed, $frekvens){
echo "retry: $frekvens" . PHP_EOL;
echo "id: $id" . PHP_EOL;
echo "data: $beskjed" . PHP_EOL;
echo PHP_EOL;
ob_flush();
flush();
}
$serverTime = time();
$beskjed = hentTidspunkt($serverTime);
if (isset($_GET['t'])){
$frekvens = $_GET['t'];
}
else {
$frekvens = 5;
}
sendMelding($serverTime, $beskjed, $frekvens*1000);
function hentTidspunkt(){
$data = array(
"P1,35,50;P2,10,10;P3,25,150;P4,75,250",
"P1,38,50;P2,9,10;P3,30,150;P4,89,250",
"P1,39,50;P2,10,10;P3,35,150;P4,95,250",
"P1,34,50;P2,8,10;P3,45,150;P4,109,250",
"P1,33,50;P2,6,10;P3,55,150;P4,150,250",
"P1,30,50;P2,4,10;P3,65,150;P4,175,250",
"P1,23,50;P2,3,10;P3,65,150;P4,175,250",
"P1,43,50;P2,2,10;P3,65,150;P4,225,250",
"P1,12,50;P2,5,10;P3,50,150;P4,225,250",
"P1,15,50;P2,6,10;P3,80,150;P4,225,250",
"P1,16,50;P2,6,10;P3,100,150;P4,225,250",
"P1,25,50;P2,7,10;P3,150,150;P4,200,250",
"P1,24,50;P2,7,10;P3,149,150;P4,225,250",
"P1,18,50;P2,4,10;P3,149,150;P4,250,250",
"P1,11,50;P2,3,10;P3,115,150;P4,245,250",
"P1,45,50;P2,7,10;P3,70,150;P4,244,250",
"P1,45,50;P2,5,10;P3,60,150;P4,244,250",
"P1,45,50;P2,5,10;P3,50,150;P4,200,250",
"P1,45,50;P2,7,10;P3,40,150;P4,200,250",
"P1,50,50;P2,10,10;P3,140,150;P4,200,250"
);
$tilfeldig = rand(0,count($data)-1);
return $data[$tilfeldig];
}
?>
So, I've never written php until today, and I'm trying to implement a cache breaking system on a wordpress site that has some React components living inside it. So inside of the footer-home.php file I have this:
</div> <?php // close #app ?>
</main>
<div class="container footer">
<div class="row">
<div class="col-sm-12">
<div id="instagram"></div>
</div>
</div>
<?php get_footer('shared') ?>
</div>
</div><?php //close container ?>
<?php
function grab_hashed_bundle_script() {
$path = '/client/';
$fileName = null;
$dirJS = new DirectoryIterator($path);
foreach ($dirJS as $file) {
if (pathinfo($file, PATHINFO_EXTENSION) === 'js') {
$fileName = basename($file);
break;
}
}
return $fileName;
}
$bundle_js = grab_hashed_bundle_script();
?>
<script src="/client/<?php echo $bundle_js ?>"></script>
<?php wp_footer(); ?>
</body>
</html>
I know this is ugly AF and hacky, so if anyone can point out a better way to do this, I'm all ears.
The reason I need to do this is I'm having webpack add a random 6-digit hash to the bundle.js filename(as in bundle-123456.js) every time we run a new build. Previously, we just had a regular script tag in this footer file like so:
<script src=/client/bundle.js"></script> but clients' browsers would end up caching bundle.js even after we had updated it requiring customers to have to empty their cache in order to get the new .js files.
Any help is greatly appreciated.
Also, I'm not trying to cache bust with a param as suggested in the comment. I'm trying to bust based on the random hash that I'm having webpack insert into the name of the bundle.js file upon building.
This is the solution one of my co-workers came up with:
Inside of functions.php:
/**
* Grab Hashed Bundle Files
*/
function enqueue_hashed_bundle_files() {
// soooo gross. would love to know of a cleaner way.
$build_dir = get_theme_root() . '/../../../client/build/';
$all_files = scandir($build_dir);
$css_files = array();
$js_files = array();
foreach( $all_files as $file ){
$pathinfo = pathinfo($file);
switch( $pathinfo['extension'] ){
case 'js':
array_push($js_files, $file);
break;
case 'css':
array_push($css_files, $file);
break;
default:
break;
}
}
// now that we have the filenames, we can access them directly with the
// absolute url
$base_url = get_option('siteurl') . '/client/';
wp_enqueue_script( 'bundlejs', $base_url . $js_files[0], array(), null, true );
wp_enqueue_style( 'bundlecss', $base_url . $css_files[0], array(), null );
}
Change your request for the js file to have a query param instead of a random string in the filename.
See this post. The browser shouldn't cache it with a query string.
i want insert user in db mysql, i have a controller php, im validate if user exist in db through a function, then if or not exist i want show alert function an redirect to php page, for that im using:
<?php
if(dao::existUser($user)) {
echo "<script type=\"text/javascript\">\n";
echo "alert('user exist!');\n";
echo "window.location = ('../insertUser.php');\n";
echo "</script>";
}
this function works!! but
i want to encapsulate the function in a method to later call it
example:
<?php
class Utils {
static function responseText($message, $url) {
echo "<script type=\"text/javascript\">\n";
echo "alert('"+$message+"');\n";
echo "window.location = ('"+$url+"');\n";
echo "</script>";
}
}
then, in my controller:
<?php
if(dao::existUser($user)) {
Utils::responseText("user exist",'../insertUser.php');
}
but not work, and after call responseText, my page goes blank
I don't know what is wrong ( likely a quoting issue ), but I would suggest using a HEREDOC style for this and return the text not output the HTML from the class by itself. Latter it could be hard to track where this output is coming from by looking just in the class that calls it. By doing echo Utills::.. you'll be able to easily see it's outputting something, whiteout having to look into what the class does.
So like this.
<?php
class Utils {
static function responseText($message, $url) {
return <<<HTML
<script type="text/javascript">
alert('$message');
window.location = '$url';
</script>
HTML; //nothing can go here no space ( before or after ) and not even this comment, nothing but HTML; litterally
}
}
echo Utils::responseText("user exist",'../insertUser.php');
HEREDOCs are a way of doing a text block without using any quotes, beware of the note i put in comments... In this case it makes the Javascript string so much more simple when you don't have to manage quote usage.
Another suggestion for this class if it is to be a collection of static methods, you can make it where it can't be instantiated ( created using new class() ) Like this
<?php
class Utils {
private function __construct(){} //no instantion
private function __clone(){} //no cloning
This way you don't accidentally do $U = new Utils(); $U->responseText(..) It's a little thing but it will insure all the methods of this class stay static. It's just a design thing I like to do, on singletons and static classes
UPDATE your issue is you are using the + to concat in PHP where you should be using the . The + is good for Javascript not so much for PHP
And the way you have it with " double quotes concat is unnecessary, instead of
echo "alert('"+$message+"');\n";
Try
echo "alert('$message');\n";
If i understand you properly bind javascript to php.
<?php
$script = '<script type="text/javascript">';
$script .= 'function showAlert(){';
$script .= 'alert("Hello World.");';
$script .= '}';
$script .= '</script>';
echo $script;
?>
Than after page has loaded you can call it !
<script type="text/javascript">
window.onload = function () {
showAlert();
}
</script>
Hello I just started working with CodeIgniter framework. My current directory structure is
Demo(Project name)
+System
+Application
-Controllers
demo.php
+Model
-Views
view_demo.php
-Js
ajax.js
jquery.js
Please tell me how to include .js files in view_demo.php.
Thanks
Raj
You need to use the base_url() to include the javascript file in your VIEW.
So, in the view_demo.php file:
<script type="text/javascript" src="<?=base_url()?>js/jquery.js" ></script>
<script type="text/javascript" src="<?=base_url()?>js/ajax.js" ></script>
You will need the URL helper loaded. To load the helper you need to put on your demo.php controller:
$this->load->helper('url');
You can also autoload on \config\autoload.php on the helpers array.
More info about base_url(): http://www.codeigniter.com/user_guide/helpers/url_helper.html#base_url
https://codeigniter.com/user_guide/general/styleguide.html#short-open-tags
You wouldn't include JS files within the PHP, they would be output as script tags within the HTML you produce which you may be producing as output from the PHP script.
As far as I know, there is no built in CodeIginiter function to include this output like there is for CSS using the link_tag() function provided by CI. I've added a function called script_tag() to the system/helpers/html_helper.php file from CI. The function is:
if ( ! function_exists('script_tag')) {
function script_tag($src = '', $language = 'javascript', $type = 'text/javascript', $index_page = FALSE)
{
$CI =& get_instance();
$script = '<scr'.'ipt';
if (is_array($src)) {
foreach ($src as $k=>$v) {
if ($k == 'src' AND strpos($v, '://') === FALSE) {
if ($index_page === TRUE) {
$script .= ' src="'.$CI->config->site_url($v).'"';
}
else {
$script .= ' src="'.$CI->config->slash_item('base_url').$v.'"';
}
}
else {
$script .= "$k=\"$v\"";
}
}
$script .= "></scr"."ipt>\n";
}
else {
if ( strpos($src, '://') !== FALSE) {
$script .= ' src="'.$src.'" ';
}
elseif ($index_page === TRUE) {
$script .= ' src="'.$CI->config->site_url($src).'" ';
}
else {
$script .= ' src="'.$CI->config->slash_item('base_url').$src.'" ';
}
$script .= 'language="'.$language.'" type="'.$type.'"';
$script .= ' /></scr'.'ipt>'."\n";
}
return $script;
}
}
Then in your PHP code you can do:
echo script_tag('content/js/jquery-1.4.2.js');
I store my javascript in a subdirectory of my view folder so the file path is relative to the view being called and I omit the base_url().
Another technique I adopted was to define an array of scripts to include in my controller, then loop through the array in my view to include them. This allows me to include specialty js functions only when needed.
$data['scripts to load'] = array('edit.js', 'menu.js', 'contact.js');
$this->load->view('myview');
Then in the view
<?php foreach($scripts_to_load as $script):?>
<script type='text/javascript' src = 'my_js/<?php echo $script;?>'>
<?php endforeach;?>
If you have script files that get loaded on every page, you can hard code them in your footer view like is described in the other answers.
The $data variable sometimes may be lost if you have nested views and you don't pass it as an argument to the children/nested views.
I found a simple solution that is working very smoothly to me:
In your current view file you setup your script like this:
$this->scripts[] = '/js/myscript.js';
at your footer or {whatever.php} file you insert this code:
<?php
if(isset($this->scripts))
foreach($this->scripts as $script) :
?>
<script src="my_asset_path/js/<?=$script;?>"></script>
<?endforeach;?>
If you need only a pice of javascript code, you can always use anonymous functions like this:
<?php
$this->RenderScript[] = function() {
?>
<script>
console.log('myjavascript code snippet');
</script>
<?}?>
and at the bottom:
<?php
if(isset($this->RenderScript))
foreach($this->RenderScript as $script) {
$script();
}
?>
Just use the standard:
<script src="/path/to/file.js" type="text/javascript" charset="utf-8"></script>
inside your view! (Not inside the PHP tags, of course.) I don't think the CodeIgniter HTML helper has any functions that you could use as an alternative to writing out the HTML yourself.
Check out Phil Sturgeon's CodeIgniter Template Library. We use a modified version of it at work.