index.html:
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="post" class="set-currency">
<div class="usd">
<label for="usd">USD</label>
<input type="number" name="usd" id="usd">
</div>
<div class="eur">
<label for="eur">EUR</label>
<input type="number" name="eur" id="eur">
</div>
<div class="gbr">
<label for="gbr">GBR</label>
<input type="number" name="gbr" id="gbr">
</div>
<button type="sumbit" class="submit-rates" name="submit-rates">Set Rates</button>
</form>
<br>
<form method="post" name="exchange-currency">
<div class="needed-currency">
<label for="needed">Needed currency</label>
<select name="needed" id="needed">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbr">GBR</option>
<option value="uan">UAN</option>
</select>
</div>
<div class="base-currency">
<label for="base">Base currency</label>
<select name="base" id="base">
<option value="usd">USD</option>
<option value="eur">EUR</option>
<option value="gbr">GBR</option>
<option selected="selected" value="uan">UAN</option>
</select>
</div>
<div class="converted-currency">
<label for="amount">Amount:</label>
<input type="number" id="amount" name="amount">
<label for="calculated">Converted</label>
<input type="number" id="calculated" name="calculated">
<button type="sumbit" name="convert">Convert</button>
</div>
</form>
<script src="script.js"></script>
</body>
</html>`
script.js:
window.addEventListener("load", function () {
console.log("php es una mierda");
let rates = {};
// document.querySelector(".submit-rates").addEventListener("click", function () {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
rates = JSON.parse(this.response);
}
};
xmlhttp.open("GET", "converter.php", true);
xmlhttp.send();
// })
})
converter.php:
<?php
if (isset($_POST['submit-rates'])):
$usdRate = (int)$_POST['usd'];
$eurRate = (int)$_POST['eur'];
$gbrRate = (int)$_POST['gbr'];
// echo "$usdRate $eurRate $gbrRate";
endif;
$rates = [
"usd" => $usdRate,
"eur" => $eurRate,
"gbr" => $gbrRate];
echo json_encode($rates);
file_put_contents("./rates.json", json_encode($rates));
?>
I have to do a currency converter where a user sets the rates, using JavaScript and PHP.
I decided to transfer data through JSON, and it works like this:
the whole thing console logs: {"usd":null,"eur":null,"gbr":null} and when I press "Set Rates" button, nothing changes.
how can I transfer the data with rates properly?
no estas usando json para usar json debes adicionar la libreria jquery
you are not using Json, if you wanna use Json, you should add jquery library
html
<!-- change your button -->
<button type="button" onclick="registroModificacion()">Convert</button>><
<!-- add at the end of yout page. you have to use jquery library -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js" ></script>
<script>
function registroModificacion(){
//get values of your form by id
const needed = $('#needed').val();
const usd= $('#usd').val();
$.ajax({
url:'paginaEn.php',
type:"POST",
data: {needed:needed,usd:usd},
success:function(r){
alert(r);
},
})
}
</script>
paginaEn.php
<?php
$usd= $_POST['usd'];
$needed= $_POST['needed'];
echo $needed." ".$usd;
?>
Related
I have a small sidebar form that submits user data. It is all functional for anyone in the USA but if someone from overseas tries to submit the form, it fails. I even logged into the same user account as the one overseas and the form submits for me. I have never encountered an issue like this with GAS. The account the user is logged into owns the spreadsheet that the script is housed in and he has tried both local and US IP addresses to submit the data (not sure if this even matters.) What do I need to change/include in my scripts to allow all users to be able to submit the form? Would creating a Webapp and trigger be a fix?
Code.gs
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
//PROCESS FORM DATA
function processForm(formObject){
var notes = [formObject.client,
formObject.website,
formObject.email,
formObject.plan];
var mTabs = [formObject.client,
formObject.plan,
formObject.timeAllowed,
'',
'',
'00:00:00.000'];
pushToSheets(notes,mTabs);
}
//INCLUDE HTML PARTS, EG. JAVASCRIPT, CSS, OTHER HTML FILES
function include(filename) {
return HtmlService.createHtmlOutputFromFile(filename).getContent();
}
//THIS FUNCTION IS USED TO PUSH DATA TO EACH RESPECTIVE SHEET FROM THE SIDEBAR FORM SUBMISSION
function pushToSheets(notes,mTabs) {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var noteTab = ss.getSheetByName('NOTES');
var sheetArr = ['JAN','FEB','MAR','APR','MAY','JUN','JUL','AUG','SEPT','OCT','NOV','DEC'];
// var sheetArr = ['JAN','FEB'];
var nLast = noteTab.getLastRow();
noteTab.insertRowBefore(nLast+1);
noteTab.getRange(nLast+1, 1,1,4).setValues([notes]);
noteTab.getRange(2,1,nLast+1,17).sort([{column: 4, ascending: true}, {column: 1, ascending: true}])
for(var x = 0; x < sheetArr.length; x++) {
var sheet = ss.getSheetByName(sheetArr[x]);
var sLength = sheet.getLastRow();
sheet.insertRowBefore(sLength-1);
sheet.getRange(sLength-1, 1,1,6).setValues([mTabs]);
sheet.getRange(2, 1,sLength,11).sort([{column: 2, ascending: true}, {column: 1, ascending: true}])
}
}
Index.html
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<?!= include('JavaScript'); ?> <!-- See JavaScript.html file -->
<title>Contact Details</title>
</head>
<body class="bg-secondary text-light">
<div class="container">
<?!= include('Form'); ?> <!-- See Form.html file -->
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.0/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js" integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI" crossorigin="anonymous"></script>
<script>
$('#timeAllowed').keypress(function() {
var regex = new RegExp("^[0-9]");
var key = String.fromCharCode(event.charCode ? event.which : event.charCode);
if (!regex.test(key)) {
event.preventDefault();
return false;
}
if(this.value.length == 2){
this.value = this.value+':';
}
if(this.value.length == 5){
this.value = this.value+':00';
}
if(this.value.length > 7) {
return false;
}
});
</script>
</body>
</html>
Form.html
<form id="myForm" onsubmit="handleFormSubmit(this)" autocomplete="off">
<div class="form-group">
<label for="client">Client</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="clint" name="client" placeholder="Client Name">
</div>
<div class="form-group">
<label for="gender">Plan</label>
<select class="form-control form-control-sm" id="plan" name="plan" required>
<option value="" selected disabled>Choose...</option>
<option value="00 hosting">00 hosting</option>
<option value="01 slim">01 slim</option>
<option value="02 basic">02 basic</option>
<option value="10 special">10 special</option>
<option value="99 coming up">99 coming up</option>
</select>
</div>
<div class="form-group">
<label for="last_name">Time Allowed</label>
<input class="form-control form-control-sm" type="text" class="form-control" pattern="[0-9][0-9]:[0-9][0-9]:[0-9][0-9]" title ="00:00:00" id="timeAllowed" name="timeAllowed" placeholder="00:00:00">
</div>
<div class="form-group">
<label for="email">Email</label>
<input class="form-control form-control-sm" type="email" class="form-control" id="email" name="email">
</div>
<div class="form-group">
<label for="website">Website</label>
<input class="form-control form-control-sm" type="text" class="form-control" id="website" name="website">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
JavaScript.html
<script>
// Prevent forms from submitting.
function preventFormSubmit() {
var forms = document.querySelectorAll('form');
for (var i = 0; i < forms.length; i++) {
forms[i].addEventListener('submit', function(event) {
event.preventDefault();
});
}
}
window.addEventListener('load', preventFormSubmit);
function handleFormSubmit(formObject) {
google.script.run.processForm(formObject);
document.getElementById("myForm").reset();
}
</script>
Looks like I just needed to add this as a Webapp and that fixed the issue. Thank you for the suggestions!
//OPEN THE FORM IN SIDEBAR
function showFormInSidebar() {
var form = HtmlService.createTemplateFromFile('test').evaluate().setTitle('New Client');
SpreadsheetApp.getUi().showSidebar(form);
}
function doGet() {
var form = HtmlService.createTemplateFromFile('Index').evaluate().setTitle('New Client');
form.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return form;
}
test.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<center>
<embed type="text/html" src="redacted" width="290" height="800">
</center>
</body>
</html>
I'm creating a form, however, when I try to submit the form using onclick event, I get the following error Uncaught ReferenceError: postAcmgForm is not defined at HTMLButtonElement.onclick
I did try including the tag inside the <head> tag and before the </body> tag and still, it doesn't work. The path mentioned in the src element is correct.
Following is the code
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<style>
.inline-div {
float: left;
}
</style>
<script language="JavaScript" type="text/javascript" src="../controller/formcontroller.js" /></script>
</head>
<body>
<div class="container-fluid">
<div id="leftDiv" class="inline-div col-md-3">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<form action="../controller/acmg_controller.php" method="POST" target="_blank">
<!--<form method="POST">-->
<div class="form-group">
PMID:
<input type="text" class="form-control form-control-sm" id="pmid" name="pmid">
</div>
<div class="form-group">
ACMG Category:
<select class="form-control form-control-sm" id="ACMG" name="ACMG">
<option value="FUNCTIONAL STUDY | 9">Functional Studies</option>
<option value="ALLELIC | 10">Patients / Allelic data</option>
<option value="CO-SEGREGATION | 11" option="11">Disease co-segregation</option>
<option value="DE NOVO | 12" option="12">De novo mutation</option>
<option value="CASE CONTROL | 13" option="13">Case-control studies</option>
<option value="PHENOTYPE | 14" option="14">Phenotype/family history</option>
</select>
</div>
<div class="form-group">
Evidence Supports:
<select class="form-control form-control-sm" id="Evidence" name="Evidence">
<option value="Supports Benignnes">Supports Benignness</option>
<option value="Supports Pathogenic">Supports Pathogenic</option>
</select>
</div>
<div class="form-group">
<label for="summary">Summary:</label>
<textarea class="form-control" id="text" name="text" rows="8"></textarea>
</div>
<div class="form-group">
<input type = "hidden" name = "genevar" id = "genevar">
<script>
var hashParams = window.location.hash.substr(1).split('&');
var temvarient = hashParams[1].split('=');
var variant = temvarient[1];
var hashParams_ = window.location.hash.substr(1).split('&');
var temgene = hashParams_[0].split('=');
var gene = temgene[1];
//document.write(gene+' '+variant);
document.getElementById('genevar').value = gene + ' ' + variant;
</script>
</div>
<div class="form-group">
<input type = "hidden" name = "mutation" id = "mutation" >
<script>
var hashParams = window.location.hash.substr(3).split('&');
var mutation = hashParams[2].split('=');
var mutationtype = mutation[1];
document.getElementById('mutation').value = mutationtype;
</script>
</div>
<div class="form-group">
<input type = "hidden" name = "vkey" id = "pvkey" >
<script>
var hashParams = window.location.hash.substr(0).split('&');
var temVkey = hashParams[3].split('=');
var vkey = temVkey[1];
document.getElementById('pvkey').value = vkey;
</script>
</div>
<div class="form-group">
</script>
<input type = "hidden" name = "genevar"id = "genevar" >
<script>
var hashParams = window.location.hash.substr(3).split('&');
var mutation = hashParams[2].split('=');
var mutationtype = mutation[1];
document.getElementById('mutation').value = mutationtype;
</script>
</div>
<button type="submit" class="btn btn-primary" onclick="postAcmgForm(this,event);" name="submit">Submit</button>
</form>
</div>
<div id="rightDiv" class="inline-div col-md-9">
<div id="pdfview">
<iframe id="pdfv"
src="...."
height="750px" width="100%">
</iframe>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
</body>
</html>
The JavaScript code in '/controller/formcontroller.js' is
function postAcmgForm(id,e){
var ACMG = $("#ACMG").val();
alert(ACMG);
$.ajax({
type : 'POST',
url : '../controller/acmg_controller.php',
dataType : 'json',
data: {
ACMG:ACMG
},
success : function(data){
$.each( data, function( key, value ){
$("#"+key).html(value));
alert(key + ":" +value);
});
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log("parse error for searchString");
}
});
}
The code in 'acmg_controller.php' is:
<?php
date_default_timezone_set("America/New_York");
$date= date('Y-m-d');
$result = $_POST['ACMG'];
$result_explode = explode('|', $result);
$data_array = array('ACMG Category' => $result_explode[0],
'ACMG ID' => $result_explode[1],
'Evidence Support' => $_POST["Evidence"],
'Summary' => $_POST["text"],
'Source' => 'PubMed',
'Date'=> $date,
'Source ID' => $_POST["pmid"],
'Vkey' => $_POST["vkey"],
'Gene Variant' => $_POST["genevar"],
'Mutation Type' => $_POST["mutation"] );
Get rid of the language="JavaScript" and don't replace it with anything. Your code looks good otherwise but the language attribute was never implemented in a standard way and was then deprecated.
Full Question: How do I redirect the user to another HTML page using my button after the program checks if the email input entered by the user is valid using the automatic email input validation built into the browser? I'm assuming I would have to use an if/else statement in JavaScript?
Code:
<!DOCTYPE html>
<html>
<head>
<title>Testing Web Page!</title>
<link rel="stylesheet" type="text/css" href="web.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Stay up to date with ecommerce trends <br>with Shopify's newsletter</h2>
<h4>Subscribe for free marketing tips</h4>
<script>
function logOptions() {
var s = document.getElementsByName('Interests')[0];
var text = s.options[s.selectedIndex].text;
console.log(text);
}
function logEmail() {
console.log(document.getElementById('emailinput').value);
}
/* function checkEmail(){
if(!document.getElementById("emailinput").checkValidity()){
alert("input not valid!");
}
}
*/
function myFunction() {
logOptions();
logEmail();
}
</script>
<!-- <div class="input form"> -->
<form id="inputform">
<input id="emailinput" type="email" placeholder="Email Address">
<span id='errorMessage'></span>
<select name="Interests">
<option value="" disabled selected>Interested in..</option>
<option value="option1">Marketing</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
<option value="option4">Option4</option>
</select>
</form>
<!-- Sign up now button -->
<div id="container">
<button id="submitButton" form="inputform" onclick="myFunction()">Sign up now</button>
</div>
<svg>
<rect width="40" height="3" style="fill:lightgreen" />
</svg>
</body>
</html>
not sure where this "automatic email input validation" that you mention,so i just put the redirection script inside myFunction.
if you try it, it will redirect to stackoverflow when you click the button.
<!DOCTYPE html>
<html>
<head>
<title>Testing Web Page!</title>
<link rel="stylesheet" type="text/css" href="web.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Stay up to date with ecommerce trends <br>with Shopify's newsletter</h2>
<h4>Subscribe for free marketing tips</h4>
<script type="text/javascript">
function logOptions() {
var s = document.getElementsByName('Interests')[0];
var text = s.options[s.selectedIndex].text;
}
function logEmail() {
console.log(document.getElementById('emailinput').value);
}
/* function checkEmail(){
if(!document.getElementById("emailinput").checkValidity()){
alert("input not valid!");
}
}
*/
function myFunction() {
logOptions();
logEmail();
window.location.href = "http://stackoverflow.com";
return false;
}
</script>
<!-- <div class="input form"> -->
<form id="inputform">
<input id="emailinput" type="email" placeholder="Email Address">
<span id='errorMessage'></span>
<select name="Interests">
<option value="" disabled selected>Interested in..</option>
<option value="option1">Marketing</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
<option value="option4">Option4</option>
</select>
</form>
<!-- Sign up now button -->
<div id="container">
<button id="submitButton" form="inputform" onclick="return myFunction();">Sign up now</button>
</div>
<svg>
<rect width="40" height="3" style="fill:lightgreen" />
</svg>
</body>
</html>
later if you already have the validation method, you can just use something like this
if(valid)
window.location.href="url to valid email page";
else
window.location.href="url to error page";
onkeyup event always check your input. and validate email regex check your input. I think it solved your requirement.
function logOptions() {
var s = document.getElementsByName('Interests')[0];
var text = s.options[s.selectedIndex].text;
console.log(text);
}
function logEmail() {
console.log(document.getElementById('emailinput').value);
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(String(email).toLowerCase());
}
function checkEmail(){
var str = document.getElementById("emailinput").value;
document.getElementById("errorMessage").innerHTML = validateEmail(str);
}
function myFunction() {
var str = document.getElementById("emailinput").value;
if(validateEmail(str)){
logOptions();
logEmail();
}
}
<!DOCTYPE html>
<html>
<head>
<title>Testing Web Page!</title>
<link rel="stylesheet" type="text/css" href="web.css" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<h2>Stay up to date with ecommerce trends <br>with Shopify's newsletter</h2>
<h4>Subscribe for free marketing tips</h4>
<!-- <div class="input form"> -->
<form id="inputform">
<input id="emailinput" type="email" placeholder="Email Address" onkeyup="checkEmail()">
<span id='errorMessage'></span>
<select name="Interests">
<option value="" disabled selected>Interested in..</option>
<option value="option1">Marketing</option>
<option value="option2">Option2</option>
<option value="option3">Option3</option>
<option value="option4">Option4</option>
</select>
</form>
<br><br>
<!-- Sign up now button -->
<div id="container">
<button id="submitButton" form="inputform" onclick="myFunction()">Sign up now</button>
</div>
</body>
</html>
I have the following problem:
I want to add textfields to my html form, send them to my script and than redirect back AND have the number of fields and their values shown.
Adding the fields via jQuery is working fine, but I can't store the values later on, because it's done via adding DIVs and they're having the same name.
Can someone point me to the right direction?
Here's the code in my index.php and in my action.php
index.php
<?php
session_start([
'cookie_lifetime' => 3600,
]);
?>
<html>
<head>
<!-- HTML5 -->
<meta charset='utf-8'>
<!-- HTML 4.x -->
<meta http-equiv='content-type' content='text/html; charset=utf-8'>
<link rel='stylesheet' href='https://unpkg.com/purecss#1.0.0/build/pure-min.css' integrity='sha384-nn4HPE8lTHyVtfCBi5yW9d20FjT8BJwUXyWZT9InLYax14RDjBj46LmSztkmNP9w' crossorigin='anonymous'>
<link rel='stylesheet' href='style/style.css'>
<meta name='viewport' content='width=device-width, initial-scale=1'>
<title>
myDrop2
</title>
<script src="scripts/jquery.js"></script>
</head>
<body>
<script>
function showLoadingMessage() {
document.getElementById('content').style.display = 'none';
var message = document.createElement('div');
message.innerHTML = '<center><h1>Wird gearbeitet, bitte warten!</h1></center>';
document.body.appendChild(message);
}
function checkRemove() {
if ($('div.d1_drops').length == 1) {
$('#remove').hide();
} else {
$('#remove').show();
}
};
$(document).ready(function() {
checkRemove()
$('#add').click(function() {
$('div.d1_drops:last').after($('div.d1_drops:first').clone());
$('div.d2_drops:last').after($('div.d2_drops:first').clone());
checkRemove();
});
$('#remove').click(function() {
$('div.d1_drops:last').remove();
$('div.d2_drops:last').remove();
checkRemove();
});
});
</script>
<center>
<div id='header'>
<b>myDrop2</b>
</div>
<br><br>
<div id='content'>
<br>
<button id='add'>[ + ]</button>
<button id='remove'>[ - ]</button>
<form action=scripts/action.php class='pure-form pure-form-aligned' onsubmit='showLoadingMessage();' method='post'>
<!-- <form action=scripts/action.php class='pure-form pure-form-aligned' onsubmit='showLoadingMessage();' method='post'> -->
<div id='settings1'>
<br>
Belichtung starten
<br><br>
<label>Warten (ms) <input name='firstwait' type='number'></label>
</div>
<div id='ventile'>
<div id='ventil1'>
<input type='radio' id='v1' name='ventile' value='1' checked='checked'>
<label for='v1'><h2>1 Ventil</h2></label>
<br><br>
<div class='d1_drops'>
<label>Tropfen 1 Dauer (ms) <input name='d1_drop[]' type='number'></label>
<br><br>
<label>Warten (ms) <input name='d1_wait[]' type='number'></label>
<br><br>
</div>
</div>
<div id='ventil2'>
<input type='radio' id='v2' name='ventile' value='2'>
<label for='v2'><h2>2 Ventile</h2></label>
<br><br>
<div class='d2_drops'>
<label>Tropfen 1 Dauer (ms) <input name='d2_drop[]' type='number'></label>
<br><br>
<label>Warten (ms) <input name='d2_wait[]' type='number'></label>
<br><br>
</div>
</div>
</div>
<div id='settings2'>
Blitzen
<br><br>
<label>Warten (ms) <input name='lastwait' type='number'></label>
<br><br>
Belichtung stoppen
<br><br>
</div>
<div id='run'>
<button type='submit'>ausführen</button>
<br>
<br>
</div>
</form>
</div>
</center>
</body>
</html>
action.php
<?php
session_start();
include ('../conf.php');
$d1_array_drop = $_POST['d1_drop'];
$d1_array_wait = $_POST['d1_wait'];
$d2_array_drop = $_POST['d2_drop'];
$d2_array_wait = $_POST['d2_wait'];
(...) do stuff with the data (..)
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
You can use sessionstorage or localstorage to remember values,if you want to output values from php ,first store them in session|files|db after redirecting , you can just output the values to js
<?php
$data=$_SESSION["data"];
?><script>
var data=<?php echo json_encode($data);?>;
</script>
I'm making an app for the overwolf app contest(http://www.overwolf.com/nvidia-app-challenge/) and in the options page, I want to be able to store the options in localStorage so I can access it from any page, at any time.
Here is my HTML page:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Battle Stats</title>
<link type="text/css" rel="stylesheet" href="style.css">
<script type="text/javascript" src="windowManagement.js"></script>
<script>
function toggleDisabled(_checked) {
document.getElementById('warnValue').disabled = _checked ? true : false;
}
//init
var ddl = document.getElementById('options_class');
var length = 5
for (var i = 0; i < length; i++){
if (ddl.options[i].value == localStorage.getItem("options_playerClass")){
ddl.options[i].selected = true;
break;
}
}
function setLocalStorageData()
{
var playerClass = '';
playerClass = document.getElementById("options_class").value;
localStorage.setItem("options_playerClass", playerClass);
alert(localStorage.getItem("options_playerClass"));
}
</script>
</head>
<body>
<div onmousedown="dragResize('BottomRight');">
<div id="content" onmousedown="dragMove();">
<div class="outlined">
<h1>Options</h1>
<form>
<p id="output"></p>
<input type="checkbox" name="options_battleStats" value="Battle Stats">Show Battle Stats<br>
<input type="checkbox" name="options_healthWarning" value="Health Warning" onchange="toggleDisalbled(this.checked);">Low Health Warning
<div class="optionInner">
<p> Warn me at:
<input type="number" name="points" min="0" max="100" step="10" value="30" class="optionValue" id="warnValue">
</p>
<p>Class:
<select name="options_class" id="options_class" class="optionValue">
<option value="smg">SMG</option>
<option value="plasma">Plasma Bomber</option>
<option value="medic">Medic</option>
<option value="rail">Rail</option>
<option value="tesla">Tesla</option>
</select>
</p>
</div>
</form>
</div>
<p>Close<span class="actionButton Middle" onclick="setLocalStorageData();">Save</p></p>
</div>
</div>
</body>
</html>
The error message is:
Uncaught TypeError: Cannot read property 'options' of null
Any help is appreciated!
Your javascript is loaded before the DOM is loaded.
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<title>Battle Stats</title>
<link type="text/css" rel="stylesheet" href="style.css">
<script type="text/javascript" src="windowManagement.js"></script>
</head>
<body>
<div onmousedown="dragResize('BottomRight');">
<div id="content" onmousedown="dragMove();">
<div class="outlined">
<h1>Options</h1>
<form>
<p id="output"></p>
<input type="checkbox" name="options_battleStats" value="Battle Stats">Show Battle Stats<br>
<input type="checkbox" name="options_healthWarning" value="Health Warning" onchange="toggleDisalbled(this.checked);">Low Health Warning
<div class="optionInner">
<p> Warn me at:
<input type="number" name="points" min="0" max="100" step="10" value="30" class="optionValue" id="warnValue">
</p>
<p>Class:
<select name="options_class" id="options_class" class="optionValue">
<option value="smg">SMG</option>
<option value="plasma">Plasma Bomber</option>
<option value="medic">Medic</option>
<option value="rail">Rail</option>
<option value="tesla">Tesla</option>
</select>
</p>
</div>
</form>
</div>
<p>Close<span class="actionButton Middle" onclick="setLocalStorageData();">Save</p></p>
</div>
</div>
<script>
function toggleDisabled(_checked) {
document.getElementById('warnValue').disabled = _checked ? true : false;
}
//init
var ddl = document.getElementById('options_class');
var length = 5
for (var i = 0; i < length; i++){
if (ddl.options[i].value == localStorage.getItem("options_playerClass")){
ddl.options[i].selected = true;
break;
}
}
function setLocalStorageData()
{
var playerClass = '';
playerClass = document.getElementById("options_class").value;
localStorage.setItem("options_playerClass", playerClass);
alert(localStorage.getItem("options_playerClass"));
}
</script>
</body>
</html>
JavaScript is getting executed prior to dom objects load. Place the entire script block at the end of the page:
<script type="text/javascript">
//All your code here
</script>
</body>
</html>