Writing variables to a second HTML file with Javascript - javascript

I've got 2 HTML files and 1 javascript file, index.html, results.html and file.js
Inside index.html I retrieve user input which is used to do some calculations inside the javascript file. The calculating starts when a button is pressed. Now I want to display the data retrieved from index.html to display on results.html so when pressing the button it should run the function and go to another page.
It all works fine to calculate and show the results on 1 page, but I don't know how to display the results on results.html.
This is how a piece of the code looks:
function berekenKoolBehoefte(){
koolBehoefte = (energieBehoefte - (eiwitBehoefte * 4) - vetBehoefte) / 4;
toonKool();
}
function toonKool(){
var uitkomstKool = document.getElementById("uitkomstKool");
uitkomstKool.innerHTML = (koolBehoefte * 4).toFixed(1) + " kcal" + " " + koolBehoefte.toFixed(1) + " gram"
}
bereken.addEventListener('click', berekenKoolBehoefte, false);
This displays all on 1 page, know function toonKool() should be display inside results.html

Your best bet in this case is to use:
server side to store the values and get the results from there
cookies - if it's small data, simply put it inside a cookie. For more info how to use cookies with plain javascript look here
attach your results to url and then parse them with JS. You can see how it's done here
iFrame - you can attach your results in an iframe and access the
data. This method is quite good, but for my taste - it's awful

I think you'd better:
1) Create form on your page aroud the button.
2) On form submit do calculations and put result to hidden field in the form (Or post all fields for calculation to server side). Then all arguments that you want to pass would be accessible on server on second page.
3) Display second page using GET or POST argument from previous.
Cookies is something that you may forgot to clear and it's much harder to manage them.
Calculation in iframe is much worse then using ajax. You may use ajax for partial load the second page, then all javascript variables would remain.

Related

Pass Javascript variable value to a php variable

I have a piece of php code:
....
for ($i=0; $i < count($files); $i++) { $rows = array_chunk($files, 5); }
....
Where I want to have the chunk length “5” as dynamic (to display items different way in different view port width), accordingly to the visitor’s browser’s view port width.
Exmpl:
if view port >= 800px – the chunk length = 5
if view port >= 680px – the chunk length = 4
etc…
I know that I need to get the view port size (width) via Javascript and I know how to dial with that part, but all the problem is to pass that value to a php variable to implement it in that piece of code.
So I need to use GET or POST method, I tried several ways, but I can’t make it work really.
Maybe I need to create a page loading at first, to do this calculation and redirecting then user to the main page with that value in a PHP variable or something like this?.
These kind of things should be done always with CSS and Javascript. PHP has no connection to these components. PHP is "static" while your viewport (width and height) are dynamically.
If you insist on doing it anyway then the following solution:
read data via JavaScript (keyword "SelfHTML Document height" or "SelfHTML Window height")
when you have the data, you pass the data
via $_POST and hidden input fields
via $_GET parameter or
via Ajax
The parameters you send to your PHP script can then be used.
But now again why you should not do it:
Problem A: I call your website, your PHP has received all possible data, has built me a layout, now I change the size, your PHP script has not noticed anything, and I have problems with the operation of your page.
Problem B: The values can open an unwanted security vulnerability, so I could pass e.g. as width or height or other information in the worst case a script via these parameters to infiltrate your server, ie you must ALWAYS validate these values.

Why doesn't diffbot see the price here?

I'm using diffbot to scrape products. It gets things right on most sites, and if it doesn't the custom API usually allows me to easily tweak until correct. However there are a few cases that are baffling me.
I know diffbot doesn't execute javascript in the custom API preview window, but for the product endpoint, it should always execute it when a request is made to the API (e.g. from the diffbot client in a Python shell).
Foot asylum
For products on this website, e.g. https://www.footasylum.com/hugo-boss-three-pack-tshirt-103678/, the offerPrice field is empty. I can see the price is in a div#priceFrm, so I try to edit and add a custom selector on that field to this effect. However even when making a new API call from the Python shell, the response is 'offerPrice': ''.
This price is obviously being added by Javascript, but why can't diffbot deal with that? What can I do about it?
I can also see the price I want can be found in some JSON data inside a <script>. Normally I could just scrape it from there, with //script[contains(text(), "dataLayer")]/text() followed by a regex. However in another diffbot custom field I defined a selector script:contains(dataLayer) and even this is blank.
Any ideas on getting the price from this product with diffbot?
Nike
I'm also trying to get the price from https://www.nike.com/gb/t/flyknit-trainer-shoe-GBXjsV/AH8396-600
The first problem is the preview window of custom API just gives a 500 error weirdly.
Next I edit the offerPrice field with a custom selector of div[data-test=product-price], however this field doesn't hit anything - even when called from client in Python shell.
Footlocker
Finally on this site https://www.footlocker.co.uk/en/p/jordan-1-flight-2-men-shoes-6671?v=314100340604#!searchCategory=all diffbot cannot seem to get product image.
The images are loaded by "scene7", and with XPATH can be found with //div[#class="s7thumb"][#data-namespace="s7classic"]/#style and then parsing out the "background-url".
I tried to at least get the style attribute with diffbot using the selector div.s7thumb div[data-namespace=s7classic] and then adding the Attribute filter "style", but again nothing at all is returned.
In some cases, specific rendering of certain elements will be blocked either by Diffbot's renderer or by a target site's anti-block measures. That's why Diffbot has X-eval functionality which lets you add custom JavaScript into calls which will get executed on a target site, as if running from the console. In this case, something like the following helps:
function() {
start();
setTimeout(function() {
price = document.querySelector("[itemprop="
Offers "] [itemprop="
price "]");
currency = document.querySelector("[itemprop="
Offers "] [itemprop="
priceCurrency "]").getAttribute("content");
price.parentElement.setAttribute("style", "");
price.parentElement.innerHTML += '<h1 class="thePrice">' + price.innerText + " " + currency + '</h1>';
setTimeout(function() {
end();
}, 500);
}, 500);
}
This has been applied as a fix and the price returns now.

Javascript file for multiple html pages

I am beginner in Javascript. I am currentlyworking on a Phonegap app with it. I am stuck in between as I have 4 html pages for signup process, and I have to pass all the html pages input value to single js file as in final all data must be POSTed to server URL and also I have read on many sites that they have recommended using same js file for all the pages of your site to speed up the site. So I have two problems to solve. I searched on many sites but could not find the accurate answer.
I need to pass 4 html page's input value to single js file.
I have to make single js file for both sign-in and sign-up.
My codes for JS page is:
var firstName="";
var lastName="";
var email="";
var password="";
var retypePassword="";
var gender="";
var DOB="";
var institute="";
var course="";
var branch="";
var semester="";
var teachers = [];
function signUpStarting() {
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword+" "+gender+" "+DOB+" "+institute+" "+course+" "+branch+" "+semester+" "+teachers.join(","));
}
function signUp1() {
firstName[0] = $("#first_name").val().trim();
firstName[1] = $("#last_name").val().trim();
email = $("#email").val().trim();
password = $("#password").val();
retypePassword = $("#retype_password").val();
alert(firstName + " "+lastName+" "+email+" "+password+" "+retypePassword);
}
function signUp2() {
gender = $('#gender').find(":selected").text();
DOB = $('#DOB').val();
alert(gender+" "+DOB);
}
function signUp3() {
institute = $('#institute').find(":selected").text();
course = $('#course').find(":selected").text();
branch = $('#branch').find(":selected").text();
semester = $('#semester').find(":selected").text();
alert(institute+" "+course+" "+branch+" "+semester);
}
function signUp4() {
$(":checkbox" ).map(function() {
if($(this).is(':checked')){
teachers.push($('label[for="' + this.id + '"]').text());
}
});
signUpStarting();
}
In html pages I am calling JS functions for each pages:
On first page:
<a onclick="signUp1()" href="register-two.html">continue</a>
On second page:
<a onclick="signUp2()" href="register-three.html">continue</a>
On third page:
<a onclick="signUp3()" href="register-four.html">continue</a>
On fourth page:
<a onclick="signUp4()">continue</a>
On each transaction from one page to next I have set alert in JS, and I am getting alert with accurate values also. But after clicking the continue button from fourth page of html, I transferred the code to main signup function. I tried to see alert in signUpStarting() function but there I am getting response of just fourth page values and other values are showing nothing as the variables are null.
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
Please help me !
I am not getting how to save variable values for always without using localStorage or cookies and POSTing all data to server.And I think this would have been easier if I would know to code for all html pages for my site to single JS file.
This is exactly right. You cannot store data in memory between page loads in a web browser environment because all javascript variables are naturally destroyed when the browser navigates away from the page to a new page (even if they use the same javascript on both pages). Thus, you have to save it somewhere with more permanence: localStorage, cookies, or on the server via POST or GET.
What I would recommend is scrapping the four different html pages and simply using one html page that changes dynamically as the user fills in data. This way the browser will not eliminate data before you are ready to POST it to the server.

How to update/modify webpage content with Javascript before page load completed?

I'm trying to display a progress bar during mass mailing process. I use classic ASP, disabled content compression too. I simply update the size of an element which one mimics as progress bar and a text element as percent value.
However during the page load it seems Javascript ignored. I only see the hourglass for a long time then the progress bar with %100. If I make alerts between updates Chrome & IE9 refresh the modified values as what I expect.
Is there any other Javascript command to replace alert() to help updating the actual values? alert() command magically lets browser render the content immediately.
Thanks!
... Loop for ASP mail send code
If percent <> current Then
current = percent
%>
<script type="text/javascript">
//alert(<%=percent%>);
document.getElementById('remain').innerText='%<%=percent%>';
document.getElementById('progress').style.width='<%=percent%>%';
document.getElementById('success').innerText='<%=success%>';
</script>
<%
End If
... Loop end
These are the screenshots if I use alert() in the code: As you see it works but the user should click OK many times.
First step is writing the current progress into a Session variable when it changes:
Session("percent") = percent
Second step is building a simple mechanism that will output that value to browser when requested:
If Request("getpercent")="1" Then
Response.Clear()
Response.Write(Session("percent"))
Response.End()
End If
And finally you need to read the percentage with JavaScript using timer. This is best done with jQuery as pure JavaScript AJAX is a big headache. After you add reference to the jQuery library, have such code:
var timer = window.setTimeout(CheckPercentage, 100);
function CheckPercentage() {
$.get("?getpercent=1", function(data) {
timer = window.setTimeout(CheckPercentage, 100);
var percentage = parseInt(data, 10);
if (isNaN(percentage)) {
$("#remain").text("Invalid response: " + data);
}
else {
$("#remain").text(percentage + "%");
if (percentage >= 100) {
//done!
window.clearTimeout(timer);
}
}
});
}
Holding respond untill your complete processing is done is not a viable option, just imagine 30 people accessing the same page, you will have 30 persistent connections to the server for a long time, especially with IIS, i am sure its not a viable option, it might work well in your development environment but when you move production and more people start accessing page your server might go down.
i wish you look into the following
Do the processing on the background on the server and do not hold the response for a long time
Try to write a windows service which resides on the server and takes care of your mass mailing
if you still insist you do it on the web, try sending one email at a time using ajax, for every ajax request send an email/two
and in your above example without response.flush the browser will also not get the % information.
Well, you don't.
Except for simple effects like printing dots or a sequence of images it won't work safely, and even then buffering could interfere.
My approach would be to have an area which you update using an ajax request every second to a script which reads a log file or emails sent count file or such an entry in the database which is created by the mass mailing process. The mass mailing process would be initiated by ajax as well.
ASP will not write anything to the page until it's fully done processing (unless you do a flush)
Response.Buffer=true
write something
response.flush
write something else
etc
(see example here: http://www.w3schools.com/asp/met_flush.asp)
A better way to do this is to use ajax.
Example here:
http://jquery-howto.blogspot.com/2009/04/display-loading-gif-image-while-loading.html
I didn't like ajax at first, but I love it now.

Create a textfile from the input of an html-form with the browser (client-side)

I have an html site with a form in it and I want the user to be able to create a text/xml file depending on the input. But I wan't to avoid setting up a webserver only for this task.
Is there a good way, to do that, e.g. with Javascript? I think you can't create files with Javascript, but maybe create a data url and pass the text, so the user can save it to file?
Or is there another way to achieve this simple task without a webserver?
Solved it, somehow. I create a data url data:text/xml;charset=utf-8, followed by the XML.
function createXML() {
var XML = 'data:text/xml;charset=utf-8,<MainNode>';
var elements = document.getElementsByTagName('input'),i;
for (i in elements) {
if (elements[i].checked == true) {
XML += elements[i].value;
}
}
XML += '</MainNode>';
window.open(XML);
}
So the url looks like data:text/xml;charset=utf-8,<MainNode><SubNode>...</SubNode>...</MainNode>
Unfortunately this doesn't work for me on Chromium(Chrome) and on Firefox. It just displays the XML instead of showing a save dialog. But I think that's because of my settings and at least you can save it as a XML-file manually.
I haven't tried this but it should work.
After getting form data, system will call page A.
page A will have javascript that gets query strings and builds the page accordingly.
After finishing page build, user can save current page with following statement in javascript
document.execCommand('SaveAs',true,'file.html');

Categories