Reading data from txt file using javascript, every 5 min - javascript

I'm trying to make the website that shows current temp at home and allows me to set the temp as I want. To read temp I use raspberry pi zero and python code to save the temp in every 5 min to the .txt file. The problem is that I need to read current temp on my website from that file in let's say very 5 min. I can use:
<head>
<meta http-equiv="Refresh" content="s" />
</head>
But it doesn't look like a good choice so I though that I can use javascript and read data from the file. Unfortunately this function works only once no matter what I change in .txt file and refresh the web, output is still the same (looks like it save previous data to some kind of the global variable).
function readTextFile()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", 'text.txt', true);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
alert(allText);
}
}
}
rawFile.send(null);
}
On the left side at this picture there are data from the txt file (using php), and at the alert handler are data using javascript and submit button. These data should be the same.
So the question is: Can I read from a .txt file when its dynamicly change? And if so, how can I do it or what function use to do it? I don't know javascript very well.
I will be very grateful for help.

Using XHR to fetch records in a defined interval is not a good solution. I would recommend you to use JavaScript EventSource API. You can use it to receive text/event-stream at a defined interval. You can learn more about it here -
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
For your application, you can do this -
JavaScript -
var evtSource = new EventSource('PATH_TO_PHP_FILE');
evtSource.onmessage = function(e) {
//e.data contains the fetched data
}
PHP Code -
<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');
$myfile = fopen("FILE_NAME.txt", "r");
echo "data:". fread($myfile,filesize("FILE_NAME.txt"))."\n\n";
fclose($myfile);
flush();
?>

you need update your .txt file in some interval, for save changes,
after set attribute id="textarea"
//use jOuery
var interval = setInterval(function(){ myFunction() },5*60*1000); // 1000=1 second
function myFunction(){
$.get('server_address',{param1:1,param2:2},function(response){
//if is textarea or input
$('#textarea').val(response);
//if is block div, span or something else
//$('#textarea').text(response);
});
}
server_address - is page where you read file content, and print them .... if it is php, then file "write.php" with code like
<?php
echo(file_get_contents('some.txt'));
{param1:1,param2:2} - is object, with params, what you send to "server_address", like {action:'read',file:'some.txt'} or something other
response - is text what is print in page on "server_address"

Related

How to show only image on the url not other content even html?

I wan't to know "How to show only image on the url not other content even html?". Like see this url link of Image. This url only shows image not any other content on webpage and also see the url of website it's dynamic url not a specific image url.
So, how to achieve that?
You simply make the request to the URL of the image.
For example, if your image is called test1.png and you have it in a directory called images, you would make the URL like this:
https://your.domain/images/test1.png
If you want to hide the full path to the images and serve them through a page (so you have some control over the request for some reason), you can do something more like the following. Let's call the PHP page img.php. And the request could be like
https://your.domain/img.php/test1
<?php
$request = './default.png';
if (isset($_SERVER['PATH_INFO'])){
$request = './images'.$_SERVER['PATH_INFO'].'.png';
if (! file_exists($request)){
$request = './default.png';
}
}
// we now know we have a valid request and the file was found
header('Content-type: image/png');
header('Content-Length: '.filesize($request));
echo file_get_contents($request);
exit;
?>
With this approach you could have any number of images in the /images/ directory and serve them if they match the request.
The website in your sample maybe using the same $_SERVER['PATH_INFO'] info approach but would be dynamically creating the image using the passed variables and explode('/',$_SERVER['PATH_INFO']) along with imagecreate()
A very quick hack version would be something like the following. The request would be like this:
https://your.domain/test.php/100x50/919/222
And the very quick code, with almost no error checking could be:
<?php
function hexToColor($hx){
$rgb = array(0,0,0);
if (strlen($hx) == 3){
$rgb[0] = hexdec($hx[0].$hx[0]);
$rgb[1] = hexdec($hx[1].$hx[1]);
$rgb[2] = hexdec($hx[2].$hx[2]);
} else {
$rgb[0] = hexdec($hx[0].$hx[1]);
$rgb[1] = hexdec($hx[2].$hx[3]);
$rgb[2] = hexdec($hx[4].$hx[5]);
}
return $rgb;
}
// default values
$sizeW = 100;
$sizeH = 100;
$bg = array(0,0,0);
$fg = array(255,255,255);
if (isset($_SERVER['PATH_INFO'])){
$opts = explode('/',substr($_SERVER['PATH_INFO'],1));
$bgSet = false;
foreach($opts as $k => $v){
// check for a width x height request
if (strpos($v,'x')){
$tmp = explode('x',$v);
$sizeW = $tmp[0];
$sizeH = $tmp[1];
} elseif ($bgSet){
// must be a foreground request
$fg = hexToColor($v);
} else {
$bg = hexToColor($v);
$bgSet = true;
}
}
}
header("Content-Type: image/png");
$im = #imagecreate($sizeW,$sizeH)
or die("Cannot Initialize new GD image stream");
$background_color = imagecolorallocate($im,$bg[0],$bg[1],$bg[2]);
$text_color = imagecolorallocate($im,$fg[0],$fg[1],$fg[2]);
imagestring($im,1,5,5,$sizeW.' x '.$sizeH,$text_color);
imagepng($im);
imagedestroy($im);
exit;
?>
But I would strongly recommend a heap of error checking before using that code!
As I understand you want to dynamically update the picture.
You can see that on their main website they created a form for the entered values:
After that, on the picture URL there are all the values you need to display this image:
https://dummyimage.com/600x400/8a1a8a/232dba&text=xzcxzcnbngh
which is this image:
what you can't see is their server side, which takes the parameters 600x400/8a1a8a/232dba&text=xzcxzcnbngh, creates a picture using their server and returning it to you.
I'll suggest you to create a server side that will return a picture and text based on the given parameters.
based on your server you will need to find out how to create the picture and return it.
As you can see here, I just modified the "src" value of the and it changed the text on the photo.
which means that their server receives the request and send back the image.
If you want a simple solution you could just send back those parameters to your page scripts, and create this image element using JavaScript.
That way, your html code will be clean without even the img element tag.
create your img in JS and send put it on the html body.
Image placeholder that’s updated by scripting
HTML code:
<img id="abc" src="">
Javascript code:
var abcImage = document.getElementById('abc');
abcImage.src = 'https://dummyimage.com/600x400/000/fff';

Write data retrieved from an API using JavaScript to host server

Edit: Update - Solution
So I have achieved what I needed to do: Write data to file on the server. I am not exactly sure how things work but it seems that:
xhttp.send(data);
does not send all the data in a FormData variable but rather only the data with the "key" "data". (Sorry if I have the terminology wrong here.) So what I did is I took my object "userData" and applied the following:
userStringData = JSON.stringify(userData);
I then put the userStringData into a FormData variable as follows:
var data = new FormData();
data.append("data" , userStringData);
This then successfully wrote to the file on the sever. In the file I only had userStringData and not the "key" "data".
In my PHP file I also included a new line after every write so that each userString data would be on a new line:
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "users.txt";
$file = fopen("./AJG_Data/".$fname, 'a');
fwrite($file, $data);
fwrite($file, "\r\n");
fclose($file);
So this is working for me now. Thanks to those who offered advice and assistance.
Edit: Update:
Objective: To write data to the server using AJAX and PHP. (Please refer to original question below if necessary)
Thanks to ADyson's comments I have made a lot of progress. I have learnt that an XMHHttprequest is the way to make an AJAX request to the server. I have this code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let successString = `Thank you ${userData.athlete.firstname} you have successfully granted permission to read your data.`
document.querySelector("#message-0").innerHTML = successString;
}
};
xhttp.open("POST","/path_to_my_php_file/file_write.php", true);
xhttp.send(data);
}
On the server side I have this in my php file:
<?php
$dir = 'AJG_Data';
// create new directory with 744 permissions if it does not exist yet
// owner will be the user/group the PHP script is run under
if ( !file_exists($dir) ) {
mkdir ($dir, 0744);
}
file_put_contents ($dir.'/test1.txt', 'Hello File');
if(!empty($_POST['data'])){
$data = $_POST['data'];
$fname = "users.txt";
$file = fopen("./AJG_Data/".$fname, 'w');
fwrite($file, $data);
fclose($file);
}
?>
The directory creation section above is not necessary it was part of my trouble shooting.
The above works perfectly if I send simple FormData created as follows:
var data = new FormData();
data.append("data" , "the_text_you_want_to_save");
The problem I have is that when I try to send more complex FormData. It doesn't work. It doesn't recognise my FormData and it doesn't get past this if statement:
if(!empty($_POST['data']))
I have checked my FormData using this code:
for (var pair of data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
The above code returns the following:
token_type, Bearer
expires_at, 12345678910
expires_in, 1234
refresh_token, 1234567890abcefg...
access_token, 1234567890abcdefg...
athlete[id], 1234567
athlete[username], joe_soap
athelete[resouce_state], 2
athlete[firstname], Joe
...
...
athelete[created_at], 2017,01-03T16:07:37Z
...
...
athlete[profile], https://some.web.address/larg.jpg
So as far as I can tell I have good FormData but nothing gets written on the server side.
How can I correct this?
Thank you.
The original question follows below.
I have successfully retrieved data from the Strava API using JavaScript code. I have the data stored in a variable as a JavaScript object. I want to write the data to a file on the server.
I have spent hours searching the web and I can't find a solution. It seems this may be possible using ajax or jQuery but I can't find a simple step by step explanation of how to do this.
Bottom line: I want a simple way to write data to file on the server using JavaScript or something related to JavaScript that is quick and easy to implement. Assuming I can successfully write to file I will later want to read from file.
You would need another file on the back end, which would actually do the writing. I'll assume PHP. I'd recommend base64 encoding the data, and storing it encoded to save time.
Javascript:
if (window.XMLHTTPRequest) {
var xhttp = new XMLHTTPRequest();
} else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//Process output, get result text with this.responseText, decode base64, and parse JSON
alert(JSON.parse(window.atob(this.responseText)));
}
}
xhttp.open("POST", "file-load.php?key=" + window.btoa(JSON.stringify(value)), true);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhttp.send();
PHP:
<?php
$key = $_POST['key'];
file_put_contents("storage.txt", $key); //Set file contents
Or, if you want to append it:
<?php
$key = $_POST['key'];
$current = file_get_contents("storage.txt");
file_put_contents("storage.txt", $current . "\n" . $key);
To read the file, just use the same setup as before for javascript, but instead of file-load.php, use file-read.php:
echo file_get_contents("storage.txt");
Use the onreadystatechange to read the output.

How do I include the contents of a text file into my website?

I am making my first blog, and I want to be able to write the posts as text files on a word processor like Microsoft Word so that I can spellcheck and check for mistakes, but then include the contents of those files into my website with custom formatting using CSS (e.g. add a style attribute to the HTML like this: style='font-family: sans-serif;').
I have already tried searching around the web, and I found this website blog.teamtreehouse.com, but it didn't suit my needs because it needs the user to click a button to include the file. I also came up with some test code that relies on the FileReader API, but since I don't understand the bits parameter of the File object (I left it blank), the test page just shows undefined. Here's the code:
<!DOCTYPE html>
<html>
<head>
<title>Test Webpage</title>
</head>
<body>
<p id='output'></p><!--p tag will have styles applied to it-->
</body>
<script>
var reader = new FileReader();
reader.onload = function(e) {
var text = reader.result;
}
//What does the first parameter do? What am I supposed to put here?
// |
// |
var file = new File([ ],'test.txt');
var txt = reader.readAsText(file);
var out = document.getElementById('output');
out.innerHTML = txt+'';
</script>
</html>
Just don't read files in js in a web browser.
You can create an API with node.js and then make an http request to get this data.
Once you created the server, just do like that:
const fs = require('fs');
var content;
// First I want to read the file
fs.readFile('./Index.html', function read(err, data) {
if (err) {
throw err;
}
content = data;
// Invoke the next step here however you like
console.log(content); // Put all of the code here (not the best solution)
processFile(); // Or put the next step in a function and invoke it
});
function processFile() {
console.log(content);
}
if you want to know how to do an api, here it is: https://dev.to/tailomateus/creating-an-express-api--7hc
Hope it helps you.
In case you have *.txt files on your server you can utilize Javascript to display the content in the browser like so:
fetch('/path/to/file.txt')
.then(r => r.text())
.then(txt => document.querySelector('<a selector>').innerHTML = txt);
That approach has the drawbacks:
The urls/filenames need to be known by the Javascript
Plain txt files do not contain any formatting, so the text block wont have a headline or alike.
But all in all: Without any server side processing this is a repetitive thing, since JS from the client side cannot even trigger a directory listing, to gain all the files that should be loaded, so for each new file you create, you have to add an entry in the Javascript as well. This is a very common problem an is already solved by the various content management systems out there (Wordpress, Joomla, Drupal,…), so I would recommend to just use on of those. Btw. Grav is a purely file based CMS, that works without a backend interface as well, so a very simple solution for your problem.
In the end, I used an HTTP request to retrieve the text from a file.
function includeText() {
var xmlhttp, allElements, element, file;
allElements = document.getElementsByTagName("*");
for (let i = 0; i < z.length; i++) {
element = allElements[i];
file = element.getAttribute("insert-text-from-file");
if (file) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {element.innerText = this.responseText;}
if (this.status == 404) {element.innerText = "Contents not found";}
elmnt.removeAttribute("insert-text-from-file");
includeText();
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
return;
}
}
}

Downloading files using Header with a JS input

I have a page that has a JavaScript function that uses Post to send a variable to a php file. The problem is, that I am using "header" to download the file and my JS does not open the PHP script in a new page.
When I open the php file in a new page, it does not receive the needed variable from the JS.
I know it sounds confusing, but I hope my code can shed some light on my problem.
The short version is, I am trying to download a file that is selected by a radiobutton. I use JS to check which radiobutton is checked and then send that to my php file. Which then needs to download the file.
Thank you all in advance.
PHP:
<?php
if (isset($_POST['routenumber'])) {
if(!isset($_SESSION)){session_start();}
$routenumber = (isset($_POST['routenumber']) ? $_POST['routenumber'] : null);
$directory = ("Users/".$_SESSION['id']."/SavedRoutes/");
$routes = scandir($directory);
sort($routes);
$route = $routes[$routenumber];
$file =("Users/".$_SESSION['id']."/SavedRoutes/".$route);
header("Content-type: application/gpx+xml");
// header("Content-Disposition: attachment;Filename=".json_encode($route).".gpx");
header("Content-Disposition: attachment;Filename=route.gpx");
readfile($file);
}
?>
JS:
function fuAccountDownloadRoute(){
var i=2;
var SelectedRadio
while (i < routecounter){
var str1='radio';
var str2=JSON.stringify(i);
var result = str1.concat(str2);
if (document.getElementById(result).checked){
SelectedRadio = result.slice(5);
}
i=i+1;
}
$.post('accountPage.php',{routenumber:SelectedRadio});
}
When you open the url: http://localhost/accountPage.php in your browser it makes a GET request. You should change all the $_POST to $_GET in your code if you want to make it possible, and then you can open it like this: http://localhost/accountPage.php?routenumber=3, though it's probably not what you really want.

Deleted file is still being accessed

I have a php script to delete an old instance of a csv file and upload a new one and a javascript function to read the file. It was working fine until I added the php to delete the old file, and now for some reason the javascript function always fetches the same file even when it's changed.
I've gone in and checked the data.csv file and it's the new file but the function still fetches the old one. And if I delete the file manually the function still mysteriously accesses the data.csv file... even though it's deleted.
This is the php:
<?php
if(file_exists('upload/data.csv'))
{
unlink('upload/data.csv'); // deletes file
}
$tmp_file_name = $_FILES['Filedata']['tmp_name'];
$ok = move_uploaded_file($tmp_file_name, 'upload/data.csv');
?>
This is the javascript. Note: the variable "allText" will always be the contents of the old CSV file even if data.csv has changed or is deleted.
function LoadCSV(){
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://****.com/mailer/upload/data.csv", true);
txtFile.onreadystatechange = function() {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
ProcessCSV(allText);
}
}
}
txtFile.send(null);
}
I'm not sure why this is happening or how to fix it?
It's probably browser caching.
I like to use a random value in the url to trick the browser into thinking it is a different page:
Try this:
function LoadCSV() {
var txtFile = new XMLHttpRequest();
txtFile.open("GET", "http://****.com/mailer/upload/data.csv?nocache="+(Math.random()+'').replace('.',''), true);
txtFile.onreadystatechange = function () {
if (txtFile.readyState === 4) { // Makes sure the document is ready to parse.
if (txtFile.status === 200) { // Makes sure it's found the file.
allText = txtFile.responseText;
ProcessCSV(allText);
}
}
}
txtFile.send(null);
}
The get parameter nochache doesn't mean anything to the server or browser, but fools it into fetching a new resource every time, at the cost of losing browser caching altogether. Technically it's possible(although spectacularly unlikely) to get the same value twice, so you can add time in milliseconds or something if you want to make it totally foolproof.
Note that this will also bypass almost all other types of caches as well.

Categories