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.
Related
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'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 currently have a servlet setup to send over a list of our active servers. The method grabs the servlet data, processes it, then injects the html into the datalist tag. HTML injection process works, but when I'm splitting the array by the concat separator (which I've done before), I get no values. Below I'll explain with code examples:
HTML:
<label for="server_id_text">Server ID: </label>
<input id="server_id_text" list="server_names" name="server_id" required>
<datalist id="server_names">
<!--This gets injected with the active servers grabbed through a get request-->
</datalist>
Javascript connecting to server to get data:
Note: serverList is a global variable.
var serverList = "";
function setupAutoComplete() {
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
console.debug("server list auto comp at post mailing: " + serverList);
});
}
This method is called in the function that is called when the onload event is called in the body tag
Here are the two methods that inject the html:
function setupServerName() {
document.getElementById("server_names").innerHTML = getServerListHTML();
}
function getServerListHTML(){
console.debug("Autocomplete process running...");
var servArr = String(serverList).split('*');
var html = '';
var temp = '<option value="{serverName}">';
console.debug("Array:" + servArr.toString());
if (serverList == 'undefined' || servArr.length == 0){
console.debug("serverList is empty...");
return '';
}
for (var i =0; i < servArr.length; ++i){
html += temp.replace("{serverName}", servArr[i]);
}
console.debug("html: " + html);
console.debug("ServList size " + servArr.length);
return html;
}
When the page loads, setupAutoCompelte() is called first. Then, setupServerName() is called.
My issue is that after I load the page, I get the correct response from the server. For instance, I'll get server1*server2 as a response to the jQuery $.get(...) call. Then I go to split the string into an array, and I get back an empty html tag (<option value="">);
Also, the debug console info are as follows:
Autocomplete process running...
Array:
html: <option value="">
ServList size 1
Status with auto comp id: success
server list auto comp at post mailing: server1*server2
Thanks for the help!
I believe that your setupServerName() function is being called before the AJAX request in setupAutoComplete() returns, so your serverList is an empty string at that point. What you need to do is populate your <datalist> from inside your AJAX callback in setupAutoComplete().
// setup autocomplete datalist
function setupAutoComplete() {
var $datalist = $('#server_names');
$.get(baseURL + '/SupportPortal').then(function (data) {
// update datalist
if (!data || !data.length) {
// no servers, empty list
$datalist.html('');
} else {
// create options html:
// reduce array of server names
// to HTML string, and set as
// innerHTML of the dataset
$datalist.html(data.split('*').reduce(function (html, server) {
return html + '<option value="' + server + '">\n';
},''));
}
});
}
// on page load, setup autocomplete
$(function () {
setupAutoComplete();
});
As you can see from "debug console info":
the get function is asyncrhonous so you need to change your setupAutoComplete get part to:
$.get(baseURL + "/SupportPortal", function (data, status) {
console.debug("Status with auto comp id: " + status);
serverList = data;
setupServerName();
console.debug("server list auto comp at post mailing: " + serverList);
});
On page load try to call directly the setupServerName function within the success event of get function. A different approach is to divide the setupServerName function so that the part related to the serverList variable becomes part of another function.
The serverList variable is global but its content is filled after the setupServerName is executed.
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.]
I have the following code in my main Dancer app .pm:
package Deadlands;
use Dancer ':syntax';
use Dice;
our $VERSION = '0.1';
get '/' => sub {
my ($dieQty, $dieType, $bonus);
my $button = param('button');
$dieQty = param('dieQty');
$dieType = param('dieType');
$bonus = param('bonus');
if (defined $dieQty && defined $dieType) {
return Dice::Dice->new(dieType => $dieType, dieQty => $dieQty, bonus => $bonus)->getStandardResult();
}
template 'index';
};
true;
Here is my JavaScript:
$(document).ready(function() {
$('#standardRoll').click(function() {
$.get("/lib/Deadlands.pm", { button: '1', dieType: $("#dieType").val(), dieQty: $("#dieQty").val(), bonus: $("#bonus").val() }, processData);
function processData(data) {
$("#result").html(data);
}
});
});
I have a div in my web page called result that I want to be updated with the die roll result from Perl. Dancer keeps coming back with a 404 error in the command window when I push the submit button.
/lib/Deadlands.pm needs to be the URL of your route (probably / in this case), not the filesystem path of your Perl module.
Your AJAX request needs to point to a URL that actually exists, not a filename that has nothing to do with the web. Looks like $.get('/', ...) would do in this case.