Issues displaying data from a PHP script on HTML 5 webpage - javascript
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];
}
?>
Related
Advanced Contact Fields not updating repeater field in separate PHP file
I'm trying to dynamically add a new ACF repeater field value (course_slug) to the current user in Wordpress. The value to be added is a URL generated from a separate function. If I use the following code on the original page using a static URL value for course_slug then the new value is added fine. <?php $field_key = "field_61e9bb8b66765"; $value = get_field($field_key, "user_{$current_user_id}"); echo $value; $value[] = array("course_slug" => "http://www.exampleurl.com"); update_field( $field_key, $value, "user_{$current_user_id}"); ?> However if I run the code in a separate PHP file using two data values sent from the original page (as per below), then I receive a 500 error. url: 'http://localhost:8888/wordpress/wp-content/themes/cookable/write-course-to-user.php',data:{"userIDdata":finaluserid, "courseURLdata":tidycourseurlupdate}, success: function(data) { $('#result3').html(data); } }); write-course-to-user.php <?php $userIDfinal = isset($_REQUEST['userIDdata'])?$_REQUEST['userIDdata']:""; $courseURLfinal = isset($_REQUEST['courseURLdata'])?$_REQUEST['courseURLdata']:""; echo $userIDfinal; echo $courseURLfinal; echo "user_{$userIDfinal}"; $field_key = "field_61e9bb8b66765"; $value = get_field($field_key, "user_{$userIDfinal}"); echo $value; $value[] = array("course_slug" => $courseURLfinal); update_field( $field_key, $value, "user_{$userIDfinal}"); ?> The three test echos in there display data as expected: echo $userIDfinal; - displays 1 echo $courseURLfinal; - displays https://calendly.com/tjmdigital/cookable-1-week-1 echo "user_{$userIDfinal}"; displays user_1 Am I missing something daft here as to why the code will run fine in the original file but not in a linked one? Any advice hugely appreciated, thanks.
Server Side Events, HTML5, PHP & Javascript... index page not 'refreshing'
I found a really good article with a feature I want to add to a page, but have been stuck the entire day with one small error. For reference the tutorial is located here. Everything is working, the only thing that is not happening is the fact that the index.php webpage is not refreshing on changes made to the hosted php array. Could anyone glance at my code and tell me if I have a typo or missed part of the article? My array file - selectedSystemStateResults.php <?php $selectedSystemStateResults = ["cart", "dogsss", "cows", "zebra", "snake"]; My serverside PHP script file - selectedSystemState-script.php <?php header("Cache-Control: no-cache"); header("Content-Type: text/event-stream"); // Require the file which contains the $animals array require_once "selectedSystemStateResults.php"; // Encode the php array in json format to include it in the response $selectedSystemStateResults = json_encode($selectedSystemStateResults); echo "data: $selectedSystemStateResults" . "\n\n"; flush(); echo "retry: 1000\n"; echo "event: selectedSystemStateResultsMessage\n"; My Client side web page - index.php <?php require "selectedSystemStateResults.php"; ?> <html> <body> <?php foreach ($selectedSystemStateResults as $selectedSystemStateResult) : ?> <li><?php echo $selectedSystemStateResult; ?></li> <?php endforeach ?> </ul> <script src="/selectedSystemState-script.js"></script> </body> </html> My javascript file - selectedSystemState-script.js let eventSource = new EventSource('selectedSystemState-script.php'); eventSource.addEventListener("selectedSystemStateResultsMessage", function(event) { let data = JSON.parse(event.data); let listElements = document.getElementsByTagName("li"); for (let i = 0; i < listElements.length; i++) { let selectedSystemStateResults = listElements[i].textContent; if (!data.includes(selectedSystemStateResults)) { listElements[i].style.color = "red"; } } }); I have read this and re-read this for the past 8 hours and feel really stuck. Does anyone see any blaring php or javascript typos or could the tutorial be wrong? Please pardon the typo I had in the file names on my unedited original post. The directory shows the files all named properly.
Using this tutorial Using server-sent events I found out that the script.php file must NOT stop executing !! or (selectedSystemState-script.php) in your case . So I guess the the tutorial you linked is wrong in some point ? try this while (1) { // Every second, send a "selectedSystemStateResultsMessage" event. echo "event: selectedSystemStateResultsMessage\n"; require("selectedSystemStateResults.php"); $selectedSystemStateResults = json_encode($selectedSystemStateResults); echo "data: $selectedSystemStateResults" . "\n\n"; ob_end_flush(); flush(); sleep(1); } this is new to me but i noticed a few things : 1- the php event script file must have header text/event-stream 2- that file must not stop executing ! 3- event: is sent before data: . Hope this help EDIT After a test on your script It worked when I changed <script src="/selectedSystemState-script.js"></script> to <script src="./selectedSystemState-script.js"></script> it was calling selectedSystemState-script.js from root folder ! and generate 404 error and in selectedSystemState-script.php <?php header("Cache-Control: no-cache"); header("Content-Type: text/event-stream"); // Require the file which contains the $animals array require_once "selectedSystemStateResults.php"; // Encode the php array in json format to include it in the response $selectedSystemStateResults = json_encode($selectedSystemStateResults); // data after event flush(); echo "retry: 1000\n"; echo "event: selectedSystemStateResultsMessage\n"; echo "data: $selectedSystemStateResults" . "\n\n"; ?> and I edited selectedSystemState-script.js a bit : let eventSource = new EventSource('selectedSystemState-script.php'); eventSource.addEventListener("selectedSystemStateResultsMessage", function(event) { let data = JSON.parse(event.data); let listElements = document.getElementsByTagName("li"); for (let i = 0; i < listElements.length; i++) { let selectedSystemStateResults = listElements[i].textContent; if (!data.includes(selectedSystemStateResults)) { listElements[i].style.color = "red"; } else { listElements[i].style.color = "blue"; } } });
<script src="/selectedSystemState-script.js"></script> does not match your javascript filename selectSystemState-script.js. Verify javascript errors next time by opening the developer tools console! Another error is that you're sending the data before setting the event name. The end of selectedSystemState-script.php should be: echo "retry: 1000\n"; echo "event: selectedSystemStateResultsMessage\n"; echo "data: $selectedSystemStateResults" . "\n\n"; flush();
Access javascript variables on server php file via browser javascript
using javascript code in browser to access javascript variable in server php file ( the php file search a text file and returned result as a php variable, then I set that php variable as javascript variable) //php file on server called data.php <?php $search = 'bing'; // Read from file $lines = file('text.txt'); $linea=''; foreach($lines as $line) { // Check if the line contains the string we're looking for, and print if it does if(strpos($line, $search) !== false) { $liner=explode(': ',$line); $linea.= $liner[1]; } } echo 'Search returned: '. $linea; <script type=\"text/javascript\"> var varxxx = $linea; </script> ?> //text file on server foo: bar el: macho bing: bong cake color: blue berry mayo: ello //Java script code in browser. var xhr = new XMLHttpRequest(); xhr.open("GET","http://.........data.php",false); xhr.send(null); $Variables.setValue(5, 'varxxx'); I got reference error x is not defined if I just run http://.........data.php , it shows Search returned:"Bong" it means data.php successfully returned the result, and php $linea is Bong. so this part below in the php file is what causes the error? <script type=\"text/javascript\"> var varxxx = $linea; </script> or something wrong with my Javascript code in browser? Any help is appreciated Thanks in advance
Try "echoing" the script tag to the .html body. You're getting this error because the variable is being created on the server side only, thats why the variable is not defined. Also I recomend you to use let instead of var, let is more secure in terms of scope. //php file on server called data.php <?php $search = 'bing'; // Read from file $lines = file('text.txt'); $linea=''; foreach($lines as $line) { // Check if the line contains the string we're looking for, and print if it does if(strpos($line, $search) !== false) { $liner=explode(': ',$line); $linea.= $liner[1]; } } echo 'Search returned: '. $linea; ?> // New script <?php echo("<script> var varxxx = ".$linea." </script>") ?>
Add JavaScript function to wordpress theme
A plugin developer who developed a comments-plugin that I use has instructed me to add the following JavaScript: function WPACLoadMoreComments() { window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1; var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString(); if (WPAC.LoadComments(url, {updateUrl: false})) { window.WPACLoadMoreCount++; } } I assume he meant to put it in functions.php but the site doesn't load when I insert this code. I tried to inset it at the end, I tried to wrap it with <?php the function... ?> How do I do that correctly?
You need to add the code to a javascript file and enqueue it in functions.php, or echo it via an action hook. There's a section about including JavaScript right in the codex that's worth a read.
add below code into your functions.php file function comment_script(){ $html = "<script type='text/javascript'> function WPACLoadMoreComments() { window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1; var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString(); if (WPAC.LoadComments(url, {updateUrl: false})) { window.WPACLoadMoreCount++; } } </script>"; echo $html; } add_action('wp_footer','comment_script');
This is a Javascript function, not a PHP function. This means that you need to do the following: <?php // Your existing PHP code here ?> <script> function WPACLoadMoreComments() { window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1; var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString(); if (WPAC.LoadComments(url, {updateUrl: false})) { window.WPACLoadMoreCount++; } } </script> <?php //Your remaining PHP code ?> Another possibility is to do it this way: <?php echo "<script>"; echo " function WPACLoadMoreComments() {"; echo " window.WPACLoadMoreCount = window.WPACLoadMoreCount || 1;"; echo "var url = (new Uri(location.href)).replaceQueryParam('WPACTake', window.WPACLoadMoreCount * 20).toString();" echo " if (WPAC.LoadComments(url, {updateUrl: false})) {"; echo " window.WPACLoadMoreCount++;"; echo " }"; echo "}"; echo "</script>"; ?> The reason we're doing it this way is that Javascript is not executed on the server but on the user's browser (client side). Thus, there is no need to put the Javascript in <?php ?> tags, because you do not want it to be executed as PHP code. Since it will be executed by the browser, this means you need this code to appear in the HTML document loaded by the browser, and hence you should use echo or write it within <script> tags outside the <?php ?> Performance-wise, it is always better to put Javascript code at the end of your page. This is to make sure that any possible lags, caused by the JS code while a user's browser is loading your page, do not affect the rendering of the page.
Put it in the functions.php or footer.php file somewhere outside <?php ?> and wrap it into <script type="text/javascript">Your function here...</script>
Class Not Found Error in PHP
I am a rookie PHP and MongoDB developer. I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class elsewhere in the project named, example.php which contains code to execute a function called, clickFunction() in an Awards.php file, which returns a JSON array to the awards.html page. The source code of my files is given as follows: Awards.html <div class = "divbottom"> <div id="divAddAward"> <button class="btn" onclick="onrequest();">Add</button> </div> </div> awards.js function onrequest() { $("#divAddAward").load('branding/dataaccess/example.php'); //The full path of the example.php file in the web root alert('Test'); $.post( 'branding/dataaccess/example.php' ).success(function(resp) { json = $.parseJSON(resp); alert(json); }); } example.php <?php foreach (glob("App/branding/data/*.php") as $filename) { include $filename; } $class = new Awards(); $method = $class->clickFunction(); echo json_encode($method); Awards.php <?php class Awards extends Mongo_db { //put your code here public function __construct() { parent::__construct(); } public function clickFunction() { $array = array( 'status' => '1' ); return $array; } } The problem here is that the program is throwing me an error in example.php, Class 'Awards' not found, despite adding the for loop to include all the files. The Awards.php file is located in App/branding/data/ path and example.php is located in App/branding/dataaccess/ path. Can anyone please tell me where exactly am I going wrong? Replies at the earliest will be highly appreciated. Thank you in advance.
My guess: as you said, example.php is located in App/branding/dataaccess/, so when you do your loop you're actually searching for files in App/branding/dataccess/App/branding/data which doesn't exist so nothing is included. Try this: foreach (glob("../data/*.php") as $filename) { include $filename; }
Update example.php to <?php foreach (glob('../data/*.{php}', GLOB_BRACE) as $filename) { //Echo out each included file to make sure it's included echo $filename . '<br />'; include $filename; } $class = new Awards(); $method = $class->clickFunction(); echo json_encode($method);
hmm.. try to use spl_autoload_register(); to include or require all files at once on example.php spl_autoload_register(function($class){ require_once '../data/' . $class . '.php'; });