Update value on web page dynamically - javascript

I have a microcontroller which reads a thermocouple and sends its values to a textfile on the Raspberry Pi.
On the Pi runs a apache server which hosts my website. The website shows the value from the textfile, but to get the actual value I have to refresh the page.
index.php
<html>
<?php $temp = file_get_contents('Temp.ESP'); ?>
<header>
<h2><?php echo $temp; ?> °C</h2>
</header>
</html>
Thanks in advance

with javascript Use the setTimeout() global method to create a timer. This will refresh the content after 5000 milliseconds (5 seconds):
also don't forget to load the jquery lybrary inside the html head adding
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
setTimeout(function(){
$.get( "mydata.php", function( data ) {
$( "#mydata" ).html( data ); // this will replace the html refreshing its content using ajax
});
}, 5000);`
</script>
on the html change
<header>
<h2 id="mydata"></h2> ºC
</header>
notice the id="mydata"
the php only needs to echo the file contents
also create the file mydata.php

Related

Pushing updates to a webpage using server-sent events

I would like to post data to my PHP page and then have it update the HTML page. I followed this example of using server-sent events to push updates to a webpage.
Here is what I have right now:
output.html:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="serverData"></div>
</body>
<script type="text/javascript">
//check for browser support
if(typeof(EventSource)!=="undefined") {
//create an object, passing it the name and location of the server side script
var eSource = new EventSource("send_sse.php");
//detect message receipt
eSource.onmessage = function(event) {
//write the received data to the page
document.getElementById("serverData").innerHTML = event.data;
};
}
else {
document.getElementById("serverData").innerHTML="Whoops! Your browser doesn't receive server-sent events.";
}
</script>
</html>
send_sse.php:
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$val = 0;
if (isset($_POST['msg'])){
$val = $_POST['msg'];
}
echo "data: $val\n\n";
ob_flush();
?>
form.html:
<html>
<body>
<form action="send_sse.php" method="post">
Message: <input type="text" name="msg"><br>
<input type="submit">
</form>
</body>
</html>
The problem is that when the form posts the value, it does not update the output.html. It does output "0" and will update whenever I manually change the value of $val and save the file. However, I want the value of $val to be determined outside of the PHP file. What am I doing wrong?
The issue you are having here is that you have missed how SSE conceptually work. Your output.html page is making a GET request to your web server and executing the script send_sse.php and opening up a connection and HOLDING that connection open and waiting for updates.
When you are posting from form.html you are sending a POST request to your web server and executing the script send_sse.php on a completely different thread.
As you have not implemented any shared persistence between these two threads it will make no difference.
So to do what you want to do you will need to have code in send_sse.php that has some form of global persistence (e.g. database) and can detect new data and then flush that down to the browser.
I am not a PHP expert, but I have written an example in Node JS that uses REDIS pub/sub to provide said persistence.
I hope that helps.

$.post() Get url of php in html

I am making an html script that will use jQuery.post() method in order to use a php script. The post() method needs an url of the php code but my php code is part of the html code
What Url should i use?
<html>
<body>
<button onclick="test()">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
var test = function() {
$('--I DONT KNOW--',{testvar:"hello"});
}
</script>
<?php
$testvar = $_POST['testvar'];
echo $testvar;
?>
</body>
</html>
An empty URL is a relative URL that resolves as the URL of the current page.
$.post("", {testvar:"hello"});
(Keep in mind that since your PHP does nothing with the data except output it, and your JS does nothing with the response, this will have no visible effect outside of the Network tab of your browser's developer tools).

Setting PHP variable in <noscript>

Something like the below does not work:
<?php $nojs = false; ?>
<noscript>
<?php $nojs = true; ?>
</noscript>
As the PHP is executed regardless if JS is enabled or not. But is there a way to get a similar effect? I'm trying to set a flag if JS is disabled and then display parts of the page accordingly.
PHP is executed before javascript, so you cannot do this. You can do something such as executing a basic ajax request and storing hasjs in a session variable once the ajax page is successfully queried. You wouldn't know if it's just the fact that the ajax request wasn't successful due to something else, or if they have Javascript disabled.
Lets give this a shot anyway:
The jquery script in your head tags
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$( document ).ready(function() {
$.get( "hasjs.php", { hasjs: "1"} );
});
</script>
The PHP file (hasjs.php)
<?php
if(isset($_GET['hasjs']))
{
session_start();
$_SESSION['hasjs'] = 1;
}
?>
Then you can access the session variable to determine if they have JS based off the ajax query. Nothing stopping the user from visiting that page though if they don't have JS installed.

PHP javascript class variable value in php echo

this is simple example i want java script class variable to php echo please fix the following example to php echo value out put
<!DOCTYPE html>
<html>
<body>
<div class="example">The Book</div>
<? echo '<div class="example">The Book</div>'; ?>
<script>
function myFunction() {
var x = document.getElementsByClassName("example");
x[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
out put of java-script "The book" but php echo is '<div class="example">The Book</div>' Targeted out put of php The book
Javascript is run on the client, PHP is run on the server. If you want PHP to use the values calculated in javscript you first have to send it to the server, either through something like AJAX, or perhaps just a query string if you don't mind loading a new page or loading the same page again but with a query string appended to the URL.

Request for the simplest jquery-ajax tutorial

I am a bit new to ajax and trying to understand how it works with jQuery.
I am searching for an example for the simplest tutorial just to understand how to get started.
Let's say - that when the page loads I want that to ask for server (PHP) to insert inside body tag the words "Hello world"
How do I do that? (in the html and in the server side file)
I suggest you take a look at the jQuery documentation. The documentation for load provides an example:
$('#result').load('ajax/test.html');
that loads the content of ajax/test.html and displays it in an element with id result
We can then mimic it and call the load function inside the ready function that is executed after the page has loaded. We use the selector body to select the body element(s) and instruct the content of the(se) element(s) to be replace with the content of ajax.php
$(document).ready(function() {
$('body').load('ajax.php');
});
OK in your HTML:
<!DOCTYPE html>
<html lang="en">
<body>
<div id="my_content">Nothing here yet</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
// When jQuery is ready
$(function(){
// Get the contents of my_page.php
$.get("/my_page.php", function(data){
// When the contents of my_page.php has been 'got'
// load it into the div with the ID 'my_content'
$("#my_content").html(data);
});
});
</script>
</body>
</html>
Then in your my_page.php PHP file:
<?
// This is what jQuery will get
echo "Something is here now!";
?>
index.html
<script>
$(document).ready(function() {
$('#body').load('ajax.php');
});
</script>
<div id="body"></div>
ajax.php
<?php
echo "Hello, World!";
?>

Categories