I wrote the script below to get values from a Json file that is stored inside a industrial automation equipment. The script is inside a HTML page that is stored in a PC and replaces Div contents based on its ID. Note: I can't run any code on the industrial equipment. This is not a "real server". It just stores Json files and update its values based in real sensors.
Script inside index.html
<script>
function callback(json)
{
document.getElementById("Nro_Ensaio").innerHTML = json.Nro_Ensaio;
document.getElementById("SP_Pelotas1").innerHTML = json.SP_Pelotas;
document.getElementById("SP_Pelotas2").innerHTML = json.SP_Pelotas;
document.getElementById("PV_Pelotas1").innerHTML = json.PV_Pelotas;
document.getElementById("Status").innerHTML = json.Status;
}
</script>
<script type="text/javascript" src="http://192.168.0.103/awp/VAR_PRENSAS/ensaio.json"></script>
ensaio.json file
callback({
'Inicia': ':="ENSAIO".CMDS.LIBERA:',
'Rearme': ':="ENSAIO".CMDS.RESET:',
'Nro_Serie': ':="ENSAIO".Nro_Serie:',
'Modelo': ':="ENSAIO".Modelo:',
'Nro_Ensaio': ':="ENSAIO".Nro_Ensaio:',
'Pronto': ':="ENSAIO".Pronto:',
'Data': ':="ENSAIO".Data:',
'Hora': ':="ENSAIO".Hora:',
'SP_Pelotas': ':="ENSAIO".SP_Pelotas:',
'PV_Pelotas': ':="ENSAIO".PV_Pelotas:',
'Status': ':="ENSAIO".Status:'
});
When I open index.html in a browser I can view all values on the places that I really want, but I need a way to get this values refreshed. I tried to refresh the page using the script below, but div values flickers every time.
<script type="text/JavaScript">
<!--
function timedRefresh(timeoutPeriod) {
setTimeout("location.reload(true);",timeoutPeriod);
}
// -->
</script>
</head>
<body onload="JavaScript:timedRefresh(5000);">
How can I update div contents from the Json file every second without flickering the page?
Very important Information: I can't enable cross-domain requests on this "server".
More information about creating pages for this equipment here! http://www.dmcinfo.com/latest-thinking/blog/articletype/articleview/articleid/8567/siemens-s7-1200-web-server-tutorial--from-getting-started-to-html5-user-defined-pages
Thanks!
I tryed to do this script below.
<script>
function callback(json)
{
document.getElementById("Nro_Ensaio").innerHTML = json.Nro_Ensaio;
document.getElementById("SP_Pelotas1").innerHTML = json.SP_Pelotas;
document.getElementById("SP_Pelotas2").innerHTML = json.SP_Pelotas;
document.getElementById("PV_Pelotas1").innerHTML = json.PV_Pelotas;
document.getElementById("Status").innerHTML = json.Status;
}
setInterval(callback,1000);
</script>
<script type="text/javascript" src="192.168.0.103/awp/VAR_PRENSAS/ensaio.json"></script>
Ensaio.json Content
callback({
'Inicia': '0',
'Rearme': '0',
'Nro_Serie': '010',
'Modelo': 'CPT001',
'Nro_Ensaio': '138',
'Pronto': '0',
'Data': '18-07-2014',
'Hora': '10-02',
'SP_Pelotas': '40',
'PV_Pelotas': '1',
'Status': 'ENSAIO',
'Nome': 'Test',
'Descricao': 'Test1'
});
I tried changing the src attribute of the script tag in Javascript, but it seems as though the script tag needs to be replaced for the script to load. Here's a function that takes a script URI and an interval and then reloads the script indefinitely, without piling up a bunch of script tags:
var scriptLoader = (function () {
var head = document.getElementsByTagName("head")[0];
return function (scriptURI, interval) {
var scriptElement = null;
setInterval(function () {
var newScriptElement = document.createElement('script');
newScriptElement.type = 'text/javascript';
newScriptElement.onerror = function (error) {
throw new URIError('Could not load script ' + error.target.src);
};
if (scriptElement) {
head.replaceChild(newScriptElement, scriptElement);
} else {
head.appendChild(newScriptElement);
}
newScriptElement.src = scriptURI;
scriptElement = newScriptElement;
}, interval);
}
}());
It's used like this:
window.onload = function () {
scriptLoader("http://192.168.0.103/awp/VAR_PRENSAS/ensaio.json", 10000);
};
[EDIT: this answer is only valid if you can set Access-Control-Allow-Origin headers on your server. also, my answer is sans jquery.]
if i understand you correctly, the name for what you are trying to do is asyncronous http requests. that means that you want to get more information from a server without reloading the whole page. the javascript technology that is used to do so is called ajax or XHR. here is an example of how to use ajax. you will want to replace the URL in xmlhttp.open("GET","ajax_info.txt",true); with the (complete) URL of the file on the server you want to access, i.e. http://..... the response that your requests gets from the server is stored in xmlhttp.responseText where xmlhttp is the name of the variable assigned to the ajax request.
[EDIT: in light of new information, maybe you'd prefer reloading an iframe than the whole page? not an awesome solution but iframes don't require cross-site request.]
Related
I am opening an html page with the code below. I am also sending is data to that page with the response.write() function:
fs.readFile('./calc.html', function(error, data){
if(error){
//do nothing for now
} else if (data){
resp.writeHead(200, {'Content-Type':'text/html'});
var sum = 9;
resp.write(sum);
resp.end(data);
}
});
How do I consume the value from 'sum' in calc.html when the page opens? In the script tag in the , I'm utilizing the Window.onload method to perform an action when the page loads. The number 9 appears in the top left hand corner of the web page when it loads, so I konw it's there, I just dont know how to consume it and use it.
<script type="text/javascript">
var htmlSum = 0;
function fetchData() {
htmlSum = //How to I scrape the 'sum' variable sent into the page?????
}
window.onload = fetchData;
</script>
What you're writing here gets received as an HTML page (in this case), which is why it just displays the number "9" in the browser. If you package it inside a <script> tag it will be available as JS:
resp.writeHead(200, {'Content-Type':'text/html'});
var sum = 9;
resp.write('<script type="text/javascript">var mySumVar = ' + sum + ';</script>');
return resp.end(data); //the "return" doesn't change anything,
//but it's good practice to make sure the function ends here
...And you can then access mySumVar from your other clientside scripts. Note that this will go in the global scope, which makes it easier to access but also bad practice. You may want to package it inside some other object to avoid polluting the scope.
Instead of writing the number at the top of the page, you can write placeholders that will be replaced with your data. For example, you could use {{sum}} as a placeholder and replace {{sum}} with your sum:
fs.readFile('./calc.html', function(error, data){
if(error){
//do nothing for now
} else if (data){
resp.writeHead(200, {'Content-Type':'text/html'});
var sum = 9;
resp.end(data.replace("{{sum}}", sum);
}
});
and in your html..
<script type="text/javascript">
var number = 0;
function fetchData() {
number = {{sum}};
}
window.onload = fetchData;
</script>
If you are planning to include more logic from the serverside into your webpage, I would recommend you look into a template engine such as EJS.
There is a web page. In page source have script:
<script>
var important = [{....}];
</script>
How get information from this variable with use node.js???
In a similar situation, when information was in function:
$(function() {
_very.important ([{....}]);
I use code:
var cloudscraper = require("cloudscraper");
cloudscraper.get("link" , function(error, response, data) {
if (error) {
console.log('ERRRRRRROR');
} else {
var info = JSON.parse(data.split("_very.important(")[1].split(")")[0]);
But, I dont know how work with this problem.
var important = [{....}];
You can assign a id to the script like <script id="script"> and get the details through innerHTML like
document.getElementById('script').innerHTML
i am try to load B.php from A.php after execution in the function and pass some data using a post array from A.php to B.php within same time.
code list as follows
A.php
<script type="text/javascript">
alert_for_the_fucntion();
window.location.href = "B.php";
function alert_for_the_fucntion() {
$.post("B.php", {action: 'test'});
}
</script>
B.php
<?php
if (array_key_exists("action", $_POST)) {
if ($_POST['action'] == 'test') {
echo 'ok';
}
}
?>
for testing purpose i tried to echo something in the B.php. but currently this is not working. have i done any mistakes? or is there any possible method to do this.
Your code does this:
Tells the browser to navigate to B.php (using a GET request)
Triggers a POST request using XMLHttpRequest
The POST request probably gets canceled because the browser immediately leaves the page (and the XHR request is asynchronous). If it doesn't, then the response is ignored. Either way, it has no effect.
You then see the result of the GET request (which, obviously, doesn't include $_POST['action']) displayed in the browser window.
If you want to programmatically generate a POST request and display the result as a new page then you need to submit a form.
Don't use location. Don't use XMLHttpRequest (or anything that wraps around it, like $.ajax).
var f = document.createElement("form");
f.method = "POST";
f.action = "B.php";
var i = document.createElement("input");
i.type = "hidden";
i.name = "action";
i.value = "test";
f.appendChild(i);
document.body.appendChild(f);
f.submit();
If you want to process the results in JavaScript then:
Don't navigate to a different page (remove the line using `location)
Add a done handler to the Ajax code
e.g.
$.post("B.php", {action: 'test'}).done(process_response);
function process_response(data) {
document.body.appendChild(
document.createTextNode(data)
);
}
Try this:
Javascript:
<script type="text/javascript">
window.onload = alert_for_the_fucntion;
function alert_for_the_fucntion() {
$.post("B.php",
{
action: 'test'
},
function(data, status){
if(status=="success"){
alert(data);
}
}
);
}
</script>
PHP
<?php
if(isset($_POST['action'])){
echo $_POST['action'];
}
?>
I'm trying to use flask with url_for. The problem is that when I try to launch an alert with the value of the javascript variable everything seems ok, but when I try to launch a alert with the url_for the content of the variable is not printed. What I'm doing wrong? or What is missing in my code?
How can I pass a JavaScript variable into the url_for function?
html code:
<a class="dissable_user_btn" data-user_id="{{user.id}}" href="#" title="Change Status"><i class="fa fa-plug"></i>
</a>
JS Code:
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id) //everything ok
alert ('{{url_for('.dissable', _id=user_id)}}'); //dont print the valur of user_id
</script>
Short answer: you can't. Flask & Jinja2 render the template on the server side (e.g. Flask is translating all of the {{ }} stuff before it sends the HTML to the web browser).
For a URL like this where you're including a variable as part of the path you'd need to build this manually in javascript. If this is an XHR endpoint I'd recommend using GET/POST to transfer the values to the server as a better best practice than constructing the URL this way. This way you can use Jinja:
$(document).ready(function(){
var baseUrl = "{{ url_for('disable') }}";
$('.dissable_user_btn').click(function(event) {
var user_id = $(this).data("user_id");
// first part = url to send data
// second part = info to send as query string (url?user=user_id)
// third parameter = function to handle response from server
$.getJSON(baseUrl, {user: user_id}, function(response) {
console.log(response);
});
});
});
I found another solution for this. My problem started when I needed to pass a variable with space.
First I created a function to remove trailing and leading spaces
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
After that, I used the function and encoded the URL
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id)
user_id = strip(user_id).replace(" ","%20");
alert ('{{url_for('.dissable', _id='user_id')}}.replace('user_id',user_id);
</script>
It worked pretty nice for me!
This is how I applied to my problem
<script>
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
$(document).ready(function() {
$('#exportcountry').click(function() {
var elemento = document.getElementById("countryexportbtn");
var country = strip(elemento.textContent).replace(" ","%20");
$('#exportevent').load("{{ url_for('get_events',country = 'pais') }}".replace('pais',country));
});
});
</script>
I am busy developing a firefox extension. I am using the Add-on Builder
What it will do:
Get an ID from a PHP page (XMLHttpRequest)
Call another function and send that ID with it
That function inserts CSS with a link tag created by javascript
My Problem:
It won't work. If I alert the currenttheme variable, nothing happens. So the XMLHttpRequest doesn't seem to work.
My code:
main.js:
var Widget = require("widget").Widget;
var tabs = require('tabs');
exports.main = function() {
var pageMod = require("page-mod");
var data = require("self").data;
scriptFiles = data.url("s.js");
pageMod.PageMod({
include: "*.facebook.com",
contentScriptWhen: 'ready',
contentScriptFile: scriptFiles
});
s.js
function addCSS(theTheme) {
var s = document.createElement('link');
s.type = 'text/css';
s.rel = 'stylesheet';
s.href = theTheme+'.css';
(document.head||document.documentElement).appendChild(s);
}
function getData() {
client = new XMLHttpRequest();
try{
client.open('GET','http://localhost:8888/istyla/login/popuplogin/myaccount.php');
} catch (e){
alert( "error while opening " + e.message );
}
client.onreadystatechange = function(){
if (client.readyState ==4){
user_data = client.responseText;
window.user_data = user_data;
var currenttheme = user_data;
window.currenttheme = currenttheme;
addCSS(currenttheme);
}
}
client.send(null);
}
getData();
P.S. The CSS file is in the data folder.
Im very new to this so not sure if I can help. Have you had a look in the error console(ctrl+shift+j) if its complaining about anything? You can console.log() and it will show in here.
Maybe use the Request lib instead of XMLHttpRequest
Here is a snippet from my code:
var Request = require("request").Request;
getUserDetails : function(userID, callback)
{
Request({
url: Proxy.remoteUrl,
content : {command:'getUser',UserID:userID},
onComplete: function(response) {callback(response.json)}
}).get();
}
Content scripts run with the privileges of the page that they are in. So if the page isn't allowed to load http://localhost/, your content script won't be able to do it either. You don't get an immediate error due to CORS but the request will fail nevertheless. What you need to do is to send a message to main.js so that it does the request (extension code is allowed to request any URI) and sends the data back to the content script.
As said, the content script has the same privileged of the web page where is attached, that is meaning you're under the Same Origin Policy.
You can solve the issue as suggested, so sent a message to the add-on code (that is not restricted by the SOP) and post the result back to the content script.
Here an example how the code could be: https://groups.google.com/d/topic/mozilla-labs-jetpack/VwkZxd_mA7c/discussion