how to use javascript pass value to php or txt file [duplicate] - javascript

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
<?php
$myFile = "new.txt";
$fileOpen = fopen($myFile, 'w') or die("can't open file");
$stringData = "total;
fwrite($fileOpen, $stringData);
fclose($fileOpen);
?>
<html>
<head>
<script>
var defaultValue = 5;
var plus = 1;
var max = 100;
var total = defaultValue;
window.setInterval(
function () {
if (total > max){
total = defaultValue;
}
document.getElementById("demo1").innerHTML = total;
total = total + plus;
}, 1000);
</script>
</head>
<body>
<p id="demo"></p>
<p id="demo1"></p>
<p id="demo2"></p>
</body>
</html>
I need save the total value into txt file, and than read by txt. so that, when i refresh the browser will not re-looping, but how i get value from javascript or from div into php? (read and write per second)

You can use an AJAX request to a php file where you can save it to txt file or a database.
But, making an ajax call every second would be unnecessary traffic. Instead I think using window.onunload would be a better choice, which saves the value when the page is redirected or refrshed.
You can use the jquery bind for that as below:
$(window).bind('beforeunload', function(){
// make ajax call here
});

If you want to save very small amount of data, like here you need to save the value of total then you can use HTML 5 provided local storage which can easily contain on average 5 MB of data. Its nothing but a storage in each domain(origin) which can store 5 MB on any individual client.
It is very easy to use like.
enter code here
// Store
localStorage.totalValueHolder = total;
// Retrieve
var totalStringValue = localStorage.totalValueHolder;
total = parseInt(totalStringValue, 10)
OR
// Store`enter code here`
localStorage.setItem("totalValueHolder ", total);
// Retrieve
var totalStringValue = localStorage.getItem("totalValueHolder");
total = parseInt(totalStringValue, 10)
Hope it will answer your question. If you have further query please let us know.

Related

how to increment a global variable in JavaScript every time a function runs in Google Apps Script? [duplicate]

This question already has answers here:
How to define global variable in Google Apps Script
(8 answers)
Global variables in Google Script (spreadsheet)
(3 answers)
Closed 4 months ago.
This adapted code:
var count = 0;
function AddRecord(name) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("data");
var cell = sheet.getRange("F5");
cell.setValue(name);
cell = sheet.getRange("B2");
cell.setValue(count);
count = count + 1;
}
function startForm() {
var form = HtmlService.createHtmlOutputFromFile('AddForm');
SpreadsheetApp.getUi().showModalDialog(form, 'Add Record');
}
function addMenu() {
var menu = SpreadsheetApp.getUi().createMenu('Custom');
menu.addItem('Add Record Form', 'startForm');
menu.addToUi();
}
function onOpen(e) {
addMenu();
}
works as expected, in that it writes the expected values, name and count, to their respective cells. However, the value for count remains unchanged. How is the count variable incremented every time the AddRecord function executes?
This const counter = ((count = 0) => () => count++)(); would seem to be at least the shortest solution suggested.
Modification points:
When a function AddRecord(name) of Google Apps Script is run from google.script.run.AddRecord(name) of Javascript, unfortunately, var count = 0; is always run. By this, count is not changed from 0 every run of the function, and the value of count is not kept. I thought that this is the reason for your issue.
If you want to keep the count and when AddRecord(name) is run, you want to count up the value of count, how about the following modification? In this modification, I used PropertiesService.
Modified script:
In this modification, the value of count is kept even when the dialog is closed.
function AddRecord(name) {
var p = PropertiesService.getScriptProperties();
var count = p.getProperty("count")
count = count ? Number(count) : 0;
// This is your current script.
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("data");
var cell = sheet.getRange("F5");
cell.setValue(name);
cell = sheet.getRange("B2");
cell.setValue(count);
count = count + 1;
// Browser.msgBox(count); // If you use this, when "AddRecord" is run, you can see the current value of "count" in a dialog.
p.setProperty("count", count);
}
// When you want to reset the value of "count", please run this function.
function resetCounter() {
PropertiesService.getScriptProperties().deleteProperty("count");
}
function startForm() {
var form = HtmlService.createHtmlOutputFromFile('AddForm');
SpreadsheetApp.getUi().showModalDialog(form, 'Add Record');
}
In this modification, when AddRecord is run from Javascript, "count" is retrieved from PropertiesService and the value is increased and the updated value is stored in PropertiesService. By this, the value of "count" is kept.
Note:
At the above-modified script, only Google Apps Script is used. As another direction, if you can also use the HTML side, how about the following modification? In this modification, the value of count is cleared when the dialog is closed.
Google Apps Script side:
function AddRecord(name, count) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("data");
var cell = sheet.getRange("F5");
cell.setValue(name);
cell = sheet.getRange("B2");
cell.setValue(count);
count = count + 1;
return count;
}
function startForm() {
var form = HtmlService.createHtmlOutputFromFile('AddForm');
SpreadsheetApp.getUi().showModalDialog(form, 'Add Record');
}
HTML side: This HTML is from your showing URL.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
let count = 0;
function AddRow()
{
var name = document.getElementById("name").value;
google.script.run.withSuccessHandler(e => {
count = e;
console.log(count);
}).AddRecord(name, count);
}
</script>
</head>
<body>
Name: <input type="text" id="name" />
<input type="button" value="Add" onclick="AddRow()" />
</body>
</html>
When this script is run, when the button is clicked, count is increased. You can see it in the console of the browser.
Reference:
Properties Service

Cannot get the number of var using javascript

I have this certain problem where I cannot get the number value of 'currentStock' var data inside an HTML file using JavaScript. I have this on my HTML file in script tag:
By the way, due to the HTML being too large, and also it was not originally my script, but from a friend who was asking for some help on adding some features in it, I can't upload the whole script as it will be going to be too long. The whole HTML script has 14076 characters with 289 lines.
I have only studied java and not javascript with HTML, so I need help with this one.
<script>
window.onload = function() {
var goDown = document.getElementById('uniqueNav');
var goRight = document.querySelector('.clothesNav');
var goUp = document.querySelector('.shrink');
goDown.style.marginTop = "0px";
goRight.style.marginLeft = "5px";
goUp.style.height = "0px";
}
$('document').ready(function(){
var name = "Ombre Printed Shirt";
var price = "P499.00";
var initialStock = 0;
var currentStock = initialStock;
document.querySelector('#clothTitle').innerHTML = "" +name;
document.querySelector('#clothPrice').innerHTML = "Price: " +price;
document.querySelector('#PITitle').innerHTML = "" +name;
document.querySelector('#PIPrice').innerHTML = "Price: " +price;
document.querySelector('#currentStock').innerHTML = "CurrentStocks: " +currentStock;
}); //------------------------Change This Every Document ----------------------------//
</script>
then this in my JavaScript File:
var cStocks = document.getElementById('currentStock').data;
alert(typeof cStocks);
alert("Data in cStocks = " + cStocks);
if (!cStocks) {cStocks = 0; alert("cStocks, not a valid number");}
if ((cStocks <= 0) == true)
{
document.querySelector('.clothButton').style.display='none';
document.querySelector('.clothButtonDisabled').style.display='flex';
}
else
{
document.querySelector('.clothButton').style.display='flex';
document.querySelector('.clothButtonDisabled').style.display='none';
}
upon loading the page, the alert says thaat the data type is undefined. I don't know what's happening with my code. did I miss something?
By the way, I have JQuery on my HTML page. it says JQuery v3.3.1 as a version
It doesn't look to me like #currentStock will have a data attribute, or value attribute (which is for inputs), so of course the js returns undefined. Right now it looks like #currentStock is having the innerHTML set on the document.ready to Current Stocks: 0
You do have an accessible variable, currentStock, which is defined during document.ready. Why aren't you accessing it directly? It will have the numeric value in it already. All you can get from #currentStock is the html you generated on document.ready, and you'd have to parse the number out of it, when it's available in raw form in the js variable currentStock.

Using the same counter for a javascript function and a php query

I am seeking to increment a variable (counter) each time a DIV is clicked.
The variable of the counter is used to select a question_id in another table so I need to reference it both in JAVASCRIPT and PHP .
Here is my code:
<script type="text/javascript">
var i= 1;
$(document).ready(function(){
$("#input01, #input02, #input03, #input04, #input05").click(function(){
var value01 = $(this).attr('value');
var value02 = i;
$.post('input_answers.php',{value:value01,id_question:value02});
var value02 = i+1;
});
});
</script>
Below is the query to insert the data ('input_answer.php')
mysqli_query($connect, "INSERT INTO `answers` VALUES ('".$_POST['id_question']."' , '".$_POST['value']."' ) ");
My problem is that I'd like to incremen a variable to display a new question each time one of the DIV is clicked.
Thank you for your help.
Correct way to pass mutliple values to server is:
$.post('input_answers.php',{value:value01, id_question:value02});
Your case:
$.post(
'input_answers.php', // URL
{value:value01}, // data passed to server
{id_question:value02} // third argument, which is NOT passed to server
);
Update: correct way to increase your counter is to wait until request is over and add 1 in a callback:
$.post(
'input_answers.php',
{value:value01, id_question:value02},
function () {
// as your i is a global variable you can increase it here
i += 1
}
);

javascript function is adding data to screen but then being overridden by another function

My issue is related a function being invoked when a page is loaded, which removes the data returned by another function.
My issue
After an order is placed, the user inputs how much they wish to pay, following which their change will be calculated and displayed on the screen. I am able to see the amount of change due when I console.log(pay - rounded_total) (See JS code at end of post below).
However when I try change the div as opposed to logging to the console document.getElementById('change_due').innerHTML = (pay - rounded_total); it only remains on the screen for a matter of milliseconds before it disappears when the GET request is made again. I am sure this is because a get request is being triggered each time the document has loaded, so ideally I am wondering how best to structure my code to deal with this. I have played around with the code I currently have in every possible way at this stage, but still cannot fix the issue.
I am also aware that my class names should not begin with numbers, however my aim with this program is to improve my vanilla javascript, and get to terms with scope etc. in JS.
My code is as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<ul id="orderList">
<p class="4.75">Cafe Latte price = 4.75</p>
<p class="4.75">Flat White price = 4.75</p>
<p class="3.85">Cappucino price = 3.85</p>
</ul>
<div id="total_paid">Amount due: $0.00</div>
<div id="change_due"></div>
<form onsubmit="changeDue()">
<input type="text" id="uniqueID" />
<input type="submit">
</form>
<script src="js/getData.js"></script>
</body>
</html>
My JS code is as follows:
var rounded_total;
var change;
document.addEventListener("DOMContentLoaded", function(event) {
loadJSONDoc();
});
function loadJSONDoc()
{
var answer;
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
answer = JSON.parse(xmlhttp.responseText)
var items = answer[0].prices[0];
var total = 0;
for(var index in items) {
var node = document.getElementById("orderList");
var p = document.createElement('p');
var price = items[index];
p.setAttribute("class", price)
var textnode = document.createTextNode(index + " price = $" + price);
p.appendChild(textnode);
node.appendChild(p);
};
}
var total = 0;
var update = document.getElementsByTagName("p");
for(var i=0; i< update.length; ++i) {
update[i].onclick = function() {
var num = parseFloat(this.className).toFixed(2);
num = parseFloat(num)
total += num;
rounded_total = Math.round(total*100)/100;
document.getElementById("total_paid").innerHTML = rounded_total;
}
}
}
xmlhttp.open("GET","/items",true);
xmlhttp.send();
}
function changeDue(){
var pay = document.getElementById('uniqueID').value;
document.getElementById('change_due').innerHTML = (pay - rounded_total);
};
Again, to be clear on what I looking to implement, is that when a user has chosen their desired items, they then enter an amount into the input box, following which they submit will provide the amount of change due.
Any help on this would be greatly appreciated.
Thanks, Paul
There are different ways to fix this. But i am not able to understand as why you are using form post here and that too without the url?
you can update
function changeDue(){
...
return false; // this is avoid form submission
}
or
function changeDue(event){
...
// you can also use event.preventDefault() or stopPropagation() here. one of them should work.
}
But again both will stop the form from getting submitted to the server. When you will submit the form to the server, the current page will be refreshed and output of the form request will be displayed on the screen. Thats the reason why you are seeing it for a fraction of second. because your code updates the div and then form submit refreshes the page.
I really suggest you from good will nothing personal. Try to rewrite your code as I understand You are trying to success something with very very wrong structure.
Anyway You can try this or something similar...
function stopPost()
{
if (//something - you can skip if clause)
{
event.preventDefault();
return false;
}
}

Refresh part of my php page with setInterval()

I have a value on my PHP page and I want to refresh it per second with setInterval().
So I actually know how to refresh values with html etc. But now I want to do the same with php values. Here is my code:
<script>
setInterval(function()
{
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
},1000);
</script>
Ofc this isn't working since JS and php arent really great together.
and in my table I just simply have:
<table>
<tr>
<td>Activity:</td>
<td><p id='MachineActivity'></p><?php echo $TimeMachineActive; ?></td>
</tr>
</table>
So the problem now is, it's only refreshing when I press f5. But now I want the autorefresh. I know setInterval() worked for html. Is it possible to get this done for php code?
This should work for you:
JS Code:
<script>
setInterval(function()
{
$.ajax({
url: 'value-generation.php',
type: 'get',
success: function(response){
$("#MachineActivity").html(response)
},
});
},1000);
</script>
value-generation.php code:
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
echo $TimeMachineActive;
?>
This is how you convert php value to javascript value
<script>
setInterval(function(){
<?php
$urlMachineOnline = 'http://192.168.0.150/awp/Shredder/PLCfiles/MachineOnline.html';
// get content
$contentMachineOnline = file_get_contents($urlMachineOnline);
//remove first 2 characters
$truncateMachineOnline = substr($contentMachineOnline, 2);
//remove last 5 characters
$MachineActivityMS = substr($truncateMachineOnline, 0, -5);
//Set the value to seconds
$MachineActivityS = floor($MachineActivityMS /1000);
$formatMachineActive = 'H:i:s';
$TimeMachineActive = gmdate($formatMachineActive, $MachineActivityS);
?>
var n_val = "<?php echo $TimeMachineActive; ?>";
console.log(n_val);
},1000);
</script>
Change console and give it to your desire.
But does this make the loading time more ? Every second you are calling a remote page and checking ?
When you refresh, PHP returns the whole page again, and it cannot refresh parts of the page. So if you want just part of the page refreshed, you'll need to use iframes.
<body>
<h1>This is my main PHP page</h1>
<iframe src="[url-to-another-php-page-with-only-the-timer]"></iframe>
</body>
And then you'll have to do a separate php page with just the timer value, and serve the html with a meta tag - this meta tag will do the refresh. Meta tag is detailed in this ticket: PHP - auto refreshing page
You need to define setInterval function.
function setInterval($f, $milliseconds)
{
$seconds=(int)$milliseconds/1000;
while(true)
{
$f();
sleep($seconds);
}
}
Now call your set interval function and it should work fine.
As you know, a PHP file will make the server generate a page when you call its URI.
The way you are using your script won't make the server "regenerate" the page and update the values.
Assuming this, you can:
Externalize the php code which is in your setInterval function (ex: update_time_machine.php)
Recall the externalized PHP resource(using IFrame or a request)
Update your page through Jquery/JAVASCRIPT using the PHP script output.
Edit: Mihali's answer sounds the cleanest one.
I'm sure this will work for you
<script>
setTimeout(function(){
location.reload();
},1000); // 1000 milliseconds means 1 seconds.
</script>

Categories