I have a setup where I want to send the results of a python script asynchronously to a webpage. I currently have a HTML page setup, with a Javascript file that deals with the information dynamically.
However, I don't really understand how to get the Javascript to interact with Server-side files, seeing as its done through PHP. What do I do to set up a php file that takes the input from a text file (generated every x seconds from the python script), and sends it to the Javascript?
Probably the easiest way is to create iframe that will refresh every x seconds that points to that genereted file. Not sure if this will work in your situation.
<iframe id="genFile" src="link/to/genFile.txt"></iframe>
<script type = "text/javascript">
window.onload = function() {
setInterval(function () {
document.getElementById('genFile').contentWindow.location.reload(true);
}, 3000);
}
</script>
More complicated way is to use server side php script that will read that generated file content and setting up ajax requests to get script output every few seconds. This is better if you need to process this file between reading and outputting or when file is out of public scope.
Related
I am trying to read a project file that will be updated(occasionally) by me and my website will read it dynamically upon the loading of the page, will i have to build a server for this or can javascript handle it?
If so, could you share code that could achieve this.
Thanks in advance!!!
The problem seems to be how can one:
read a plaintext file stored on the website's local directory
use the contents of the file to modify a web page's content
This could be handled with JavaScript on the server side, but only if the server is configured to run JavaScript (like a node.js server).
Since the original question reads "will i have to build a server for this", it's probably likely that this is a vanilla server like Apache.
Most Apache servers are configured to run PHP code, so PHP is probably the simplest solution for grabbing the plaintext file.
Code below will load the contents of a plaintext file on the server into a JavaScript string, which then can be acted upon in the browser with JavaScript.
This code would go inside a <script> element in the HTML file:
function actUponProjectFile () {
// read project file on server using PHP, and store into JavaScript
// constant `projectFileString`
const projectFileString = `<?php
$pfText = file_get_contents('./my_project_file.txt');
echo $pfText; ?>`;
// insert code to act upon the `projectFileString` here
}
// run `actUponProjectFile()` after the window loads
window.onload = () => {
actUponProjectFile();
}
Save your data in a Javascript file and include it in your html
// data.js
const data = [
{
type: 'airtime',
price: 20,
size: '5GB',
},
{
type: 'electricity',
price: 10,
size: '40mw',
},
];
Then include the file in your html file
<script type="text/javascript" src="data.js"></script>
You can use nginx to share static files and use fetch request in js to get this file from server. If you have only static files you don't need to use server, nginx will be enough for you.
Problem definition:
I am programming one HTML file to be run locally in a user machine NOT FUNCTIONING AS A SERVER.
A user could run this html file locally stored in his computer. The HTML file will generate a table dynamically based on the data stored in his machine locally in a particular folder (which is always the same). This data is a JSON file.
For clarity reasons asume that the JSON file is in the same folder as the HTML file.
I have been reading a lot in the internet and in stack overflow at no avail.
For instance:
a) here with:
$.getJSON("books.json", function(json) {
console.log(json);
//access your JSON file through the variable "json"
});
does not work.
Or using this code:
jQuery.getJSON("data.json", handleJSON);
function handleJSON(result){
jQuery.each(result, printFields);
}
function printFields(i, field){
let row = field.id + " "+field.first_name + " "+field.last_name + " <br>";
jQuery("div").append(row);
}
the console says:
[Error] Failed to load resource: Preflight response is not successful (data.json, line 0)
[Error] XMLHttpRequest cannot load file:///Users/jose/CODE/HTML/ConceptsHTML/example%203/data.json. Preflight response is not successful
There are several other links of Stack overflow that I could put here. None one functions as smoothly as they say they do.
(I am using a MAC and trying the HTMLs in Safari and Chrome)
Ultimately I want of course to pass the JSON to an array to be access in other scripts of the HTML.
Note: There are some solutions where it is said that the local machine has to be run as a server and an Httprequest should be done in the machine. Well I can not do that since the users can only open the html file but nothing can be expected from them as to set the machine as as ever whatsoever.
I would be very very glad If I get a hint as to how to proceed. Right now I don't even know if this is actually possible to do.
thanks a lot
You could just use another JS file and link to it in your HTML file, and then in that JS file just make an object with the data you want.
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="json.js"></script>
<script type="text/javascript">
function fun(){
alert(json.data);
}
</script>
</head>
<body>
<button onclick="fun();">push me</button>
</body>
</html>
JS (json.js):
var json = {
data : "hello world"
};
Linking to a local JSON file cannot be done.
THE ANSWER IS:
IT IS NOT POSSIBLE TO READ LOCAL FILES (FILES IN THE USER MACHINE) WITH HTML DUE TO SECURITY REASONS.
The funny thing is that there are plenty of post telling the contrary.
I UNDERSTAND THAT IF THAT WOULD BE POSSIBLE SENSIBLE DATA MIGHT BE STOLEN.
The improvement for html future versions would be to create a way for the local. User to tell the local browser which local folder is "free" to be accesible by html.
At first, you need to parse loaded json file, because before parsing, the content is just string and you can not handle it.
So please do as below:
function handleJSON(result){
result = JSON.parse(result); // using json.parse function to convert string to a valid json model.
jQuery.each(result, printFields);
}
I hope it will be helped you.
My HTML page has a <script> tag, which embeds a Javascript source file indirectly through a PHP script, e.g.
<script src="http://my.server.com/myjs.php?version=1"></script>
Based on the parameters to myjs.php (version only being an example) the PHP file simply sets the location
header("Location: version/1/mynewfile.js");
and the browser then automatically loads mynewfile.js.
Unfortunately mynuewfile.js needs to know the URL where it is loaded from, e.g. http://my.server.com/version/1/mynewfile.js.
Without using redirection, the globally executed code in mynewfile.js simply inspects the src property of the first element. Unfortunately, this only returns http://my.server.com/myjs.php?version=1. How can mynewjsfile.js get the real (redirected) URI of the script?
Of course, the PHP file could "simply" read the JS file and set a global variable to the JS file, but redirection is a really elegant solution and should be kept if possible.
Following is what I want to accomplish:
In the html When the page loads(onload) I want to run a CGI script which is a C program to run a function in it.
I am thinking of calling a JS function onload in html:
<body onload="MyJsFunc();">
then in the JS file:
function MyJsFunc()
{
//call MyCGIfunc()
}
Now, how do I call my cgi above?
I am not sure if what I am trying to accomplish is doable or not.
Note: I cant use jquery
CGI programs are executed by making an HTTP request to them.
If you want to trigger them when a page is loaded, then the usual approach is to have the page be generated from the CGI program in the first place.
Failing that, you can use a Server Side Include to call the CGI program. (Note: You need to have your server configured to parse your HTML document for SSI directives).
<!--#exec cmd="./my_cgi" -->
If you really want to use JavaScript, then you will have to make the browser issue an additional HTTP request. This is usually done using the XMLHttpRequest object.
var myRequest = new XMLHttpRequest();
myRequest.open("GET", "/cgi-bin/my_cgi");
myReqest.send();
you can use iframe to exec cgi. as :
<iframe src="/cgi-bin/script.cgi" width="300" height="150">
I am sharing a script tag with client to deploy my web application on client's website.
Basically by this way, he can embed my app wherever he want on his site.
The script which I give him just calls one action method in my MVC application and receives a javaScript as a response.
As a fist step, this returned JavaScript inserts all js and css references (required by my application) in the client's head tag
function createScriptElement(src) {
var tmp = document.createElement("script");
tmp.src = src;
var head = document.getElementsByTagName("head")[0];
head.appendChild(tmp);
};
and then in second step, it writes the html content inside one dynamic div.
document.write(format("<div id='mycontainer'>{0}</div>{1}", AppHtml,initcalls ));
The "initcalls" contains the initial function in my app's javascript which I expect to execute immediately. So I put it in Script tag as below.
contents of initcalls are:
<script type=\"text/javascript\"> function icInitApp() { ..... }; </script>
The problem is: there are some dependencies in my application on the js references. The HTML is getting loaded before the head tag in client's page recognizes and loads the js references.
Is there any way to hold my (thus dynamically rendered) application's init function until all js references are fully loaded by head tag?
I tried giving setTimeout() with 5 seconds but it will not be proper solution accepted by client.
A similar kind of situation is discussed in the link below
How to detect if javascript files are loaded?
You can also try to use the $(window).load() event since this will be fired when the page is fully loaded.
$(window).load(function(){
//your code here
});
PS: Be aware that you will need to load the jQuery in your page to make the above code work.
You can try with jQuery:
$(document).ready(function()){
// Your code goes here
};