Use Promise to get Custom Dialog Result, Simplified Example - javascript

Beginner question here. At various points in my script I need the user to choose something from a selection of radio buttons on a CustomDialog, and then select from a second set of options based on their answer to the first dialog box, and then get that (asynchronous) response back into my main code so I can act on it further.
I can think of some ugly workarounds within my current skill-set, but after a lot of googling it looks the “right” way to handle this is with promises, so I’m trying to learn how. Eventually two promises will need to be chained, but I’m hoping I can tackle that once I understand the structure of the initial promise. What I have so far is clearly not right…
Many thanks for any and all schooling/advice.
function callRadio(myArray,myTitle){
//Call the HTML file and set the width and height
Logger.log('callRadio has been called, with this array: ',myArray);
var html = HtmlService.createTemplateFromFile('Radio_Template')
html.myArray = myArray;
var html = html.evaluate().setHeight(18.5 * myArray.length + 75);
//Display the dialog
var dialog = SpreadsheetApp.getUi().showModalDialog(html, myTitle);
};
function runsies(value){
//Receive value from .html back to .gs side. Display the value submitted from the dialog box in the Logger.
Logger.log("index of user selection is: ",value);
SpreadsheetApp.getActiveSheet().getRange(1, 1).setValue(value)
return(value);
//Fine as far as it goes , but I want to call this asynchronous output back to
// the test2 function to act on it further.
};
function test2(){ //attempt to set up my dialog calls in a promise (and later use .then to chain the follow-up question, but I don't understand the first promise structure yet)
var myTitle1 = "Select your favorite fruit"; //for testing purposes. Will otherwise be a variable string passed to test2()
var myArray1 = ["apples","bananas","grapes"]
var promise1 = new Promise(function(resolve, reject) {
var theAnswer1 = callRadio(myArray1, myTitle1).successHandler;// This calls the CustomDialog just fine, but is clearly not the right way to get at the returned value
Logger.log("What's going on inside the promise?: ",theAnswer1)//Logger returns null
if (theAnswer1 >=0) { /* if everything turned out fine */
resolve(theAnswer1);
}
else {
reject(Error("It broke"));
}
});
var x = promise1.then(function(result) {
Logger.log(result); // "Stuff worked!"
}, function(err) {
Logger.log(err); // Error: "It broke"
});
Logger.log('Your favorite fruit is: ', myArray1[x]);
//I need to chain a follow-up question, calling the dialog again based off the first answer(i.e.using callRadio(myArray2[x][1],myTitle2)).
//I think if I can get the first promise to work, I can extrapolate that to chain the second promise.
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<? for (var i = 0; i < myArray.length; i++){
?>
<div>
<input type="radio" id="<?= myArray[i] ?>" name="selection" value="<?= i ?>">
<label for=i><?= myArray[i] ?></label><br>
</div>
<? } ?>
<br>
<div>
<input type="submit" value="Submit" class="action" onclick="form_data()" >
<input type="button" value="Close" onclick="google.script.host.close()" >
</div>
</body>
<script>
function form_data(){
var value = $("input[name=selection]:checked").val();
google.script.run.withSuccessHandler().runsies(value);
google.script.host.close();
};
</script>
</html>

Related

At first it said its not a function, now its just not doing anything

Okay, I'm trying to make a cheesy accent generator to practice with RegEx. But I have a strange problem that seems unrelated to RegEx. The submit button doesn't do anything. At first the function "maccent" was just called "accent" and at that time the console said "accent" was not a function. With nothing better to go on, I assumed it was because the word "accent" was used so many other times, so I changed the function name to "maccent". Now, however, nothing happens. What's the deal? Here is my code:
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="UTF-8">
<title>Accent Generator</title>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
</head>
<body>
<p>Choose an accent</p>
<input type = "text">
<form action="">
<input type="radio" name="accent" value="German"> German<br>
<input type="radio" name="accent" value="English"> English<br>
<input type="radio" name="accent" value="Indian"> Indian
</form>
<button type="submit" onclick = "maccent()">Submit</button>
<div id = "accented"></div>
<script>
var accent = $('input[name="accent"]:checked').val();
function maccent()
{
if (accent == "German")
{
germAcc();
}
}
function germAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[w]/gi, "v")
//not if it's at the end of a word
var desire2 = desire.replace(/th/, "z")
//replace h too, but not with another z.
//wait, what? It replaces t even if its not followed by h
var desire3 = desire2.replace(/er/, "a")
//this is going to be a hard one
//er is replaced with a but only if its followed by a space or a punctuation
mark.
console.log(desire3);
}
function indAcc()
{
var sample = $("input").val()
var desire = sample.replace(/[r]/gi, "d")
//not if it's at the end of a word
//this words, but not on each indivual word
console.log(desire);
}
function itAcc()
{
}
function britAcc()
{
var sample = $("input").val();
var desire = sample.replace(/[a]/gi, "au")
var desire2 = desire.replace(/er/, "a")
//this is going to be a hard one
console.log(desire2);
//not if it's at the end of a word
}
</script>
</body>
</html>
The problem is the assignment of the "variable" accent. You are doing it at global scope (the top level), so it gets assigned when the page is first loaded.
If you move that assignment into the function maccent() (and move the work "mark" back into the comment it belongs to), your page will work.
Incidentally, the old problem was that you had a function and a variable trying to share the name accent. The variable was "winning".

Missing POST parameters in AJAX call result in undefined index warnings in PHP script

I am using AJAX for the first time so I write a code and I followed a tutorial, but when I try to send my post with ajax I am getting undefined index and I really don´t know why, I tried to search answer hear but since I am using AJAX and javascript for the first time, the code there didn´t tell me anything.
Here is my code, I would be really greatful for any help, thank you.
js method
function post() {
var name = $('meno').val();
var priez = $('priezvisko').val();
$.post( "aktualizuj.php", {
'meno': name,
'priezvisko': priez
},
function (data) {
$('#result').html(data);
}
);
}
html form...
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="prihlasenie.js"></script>
</head>
<body>
<form>
<label for="meno" >Meno:</label><input type ="text" name="meno" id="meno" value ="meno" ><br>
<label for="priezvisko" >Priezvisko:</label><input type ="text" id="priezvisko" name="priezvisko" value ="priezvisko" ><br>
<input type="button" value="ulozZmeny" onclick="post()" >
</form>
<div id="result"></div>
</body>
</html>
this where I should get from ajax/javascript
session_start();
require "pripojenie.php";
$meno = $_POST['meno'];
$priezvisko = $_POST["priezvisko"];
$login = $_SESSION['login'];
jquery doesn't serialize key:value pairs where value is undefined, i.e.
$.post(url, { foo:undefined });
results in jquery not sending any POST parameter.
The problem is because of the following lines,
var name = $('meno').val();
var priez = $('priezvisko').val();
This would look for an element meno and an element priezvisko (and then their values) as if you had a document like
<p>
<meno>...</meno>
<priezvisko>...</priezvisko>
</p>
But you're looking for elements that have meno/priezvisko as value of their id attribute(s):
var name = $('#meno').val();
var priez = $('#priezvisko').val();
You should nevertheless check the existince of the parameters in your php script. Nothing prevents another script/bot/user to invoke your script with different parameters or no parameters at all.
see also:
http://docs.php.net/isset
http://docs.php.net/filter

Better way to apply javascript scripts

Hello SO I'm relatively new to html and javascript and I currently want to make a page that will fulfill certain operations such as finding the max number of an array of numbers and factorial of a number as shown below.
and here is how I am organizing these sections
<!DOCTYPE html>
<html lang = "en">
<head>
<title>HTML/CSS Responsive Theme</title>
<meta charset = "utf-8">
<link rel = "stylesheet" href = "main.css" type = "text/css">
<meta name = "viewport" content = "width=device-width, initial-scale=1.0">
<script>
function startFactorial(number)
{
function factorial(num)
{
if(num <= 1)
return 1;
return num * factorial(num - 1);
}
document.factorials.factorialsfield.value = factorial(number);
}
function startMaxofFive(str)
{
//can actually find the max of n numbers not limited to 5
function maxoffive(string)
{
var nums = (string.match(/[-]?\d+/g));
var b = nums.map(Number);
return Math.max.apply(Math,b);
}
document.mof.moffield.value = (maxoffive(str));
}
</script>
</head>
<body>
<section id = "first">
<h3>Factorial</h3>
<form name= "factorials">
Enter a number <input type = "number" name = "factorialsfield" value = 0>
<br><br>
<input type = "button" onClick = "startFactorial(factorialsfield.value)" value = "Calculate"/>
</form>
</section>
<br>
<section id = "second">
<h3>Max of Five Numbers</h3>
<form name = "mof">
Enter 5 numbers <input type = "text" name = "moffield" placeholder = " separate each number by commas" size = 26>
<br><br>
<input type = "button" onClick = startMaxofFive(moffield.value) value = "Calculate"/>
</form>
</section>
<br>
<section id = "third">
<h3>Sum and Multiply</h3>
<form name = "operations">
Enter numbers to apply operations <input type = "text" name = "operationsfield"
</form>
</section>
</body>
</html>
What I wanted to ask you all is is there a better way to access those functions in my script without having to create another function just to use them?
Here's some suggestions:
You can use document.getElementById( id ) to get specific elements where id is the HTML's element id <element id="id_name">.
Events allow you to trigger actions based on user input. It works basically the same, but you no longer need to name the functions: element_variable.event = function() { /* ... */ }
See if the inner functions are really neccessary; see if you can edit the code where you no longer need that function (document.getElementById will probably be able to let you do that stuff)
Example:
<form id="factorials" name="factorials">
<!-- Skipping input -->
<input type="submit" <!-- ... -> />
</form>
// Javascript file
var fact = document.getElementById( "factorials" );
fact.onsubmit = function() {
/* Your code here */
}
It's generally considered best practice to move scripts to the bottom of the page before the closing body tag. This way the loading of the scripts won't interfere with page load.
You can also move your scripts to a separate file and include it:
<script src="myscripts.js"></script>
This will help keep your code more neat and organized.
You always use functions to call functions. Sounds weird but thats how it is :P
You can remove the JS calls from your DOM by adding eventlisteners to your JavaScript file just like this example:
<script>
var x = document.getElementById('test');
x.addEventListener('click', function(){
// your function magic happens here
});
</script>
<div id="test"></div>
Sorry if I understood your question wrong
I am not sure that this is what you asked for, however, it seemed like you wanted to know about other methods to get access to your javascript code or script in your HTML.
I can truly recommend you, to look into Angular for this. With Angular you can call methods in your controller, and scope data between your view (HTML) and controller (Javascript).
https://angularjs.org/
But this is just one of many options!

post form values to html

I want to POST form values and display them on another html page using Javascript. No server-side technology should be used. I have a function that posts the values but to read the values to another html page, I think I am missing something. Below is the code.
Any help? Thanks in advance.
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Untitled Page</title>
<script type="text/javascript">
function post_to_page(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
form.setAttribute("target", "formresult");
for (var key in params) {
if (params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
// creating the 'formresult' window with custom features prior to submitting the form
window.open('target.htm', 'formresult', 'scrollbars=no,menubar=no,height=600,width=800,resizable=yes,toolbar=no,status=no');
form.submit();
}
</script>
</head>
<body>
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</div>
</form>
</body>
</html>
Here is a simple example of moving data from one Window to another
<!-- HTML -->
<textarea id="foo"></textarea><br/>
<input id="bar" value="click" type="button"/>
and the real code to make it work, which assumes you pass the same origin policy
// JavaScript
var whatever = 'yay I can share information';
// in following functions `wnd` is the reference to target window
function generateWhatever(wnd, whatever) { // create the function actually doing the work
return function () {wnd.document.getElementById('foo').innerHTML = whatever};
} // why am I using a generator? You don't have to, it's a choice
function callWhenReady(wnd, fn) { // make sure you only invoke when things exist
if (wnd.loaded) fn(); // already loaded flag (see penultimate line)
else wnd.addEventListener('load', fn); // else wait for load
}
function makeButtonDoStuff() { // seperated button JS from HTML
document
.getElementById('bar')
.addEventListener('click', function () {
var wnd = window.open(window.location); // open new window, keep reference
callWhenReady(wnd, generateWhatever(wnd, whatever)); // set up function to be called
});
}
window.addEventListener('load', function () {window.loaded = true;}); // set loaded flag (do this on your target, this example uses same page)
window.addEventListener('load', makeButtonDoStuff); // link button's JavaScript to HTML when button exists
You can't get POST values using JavaScript. You can use GET method to pass values.
If you are using html5 you can use localStorage. Otherwise a query string or cookies are your other options.
You said you didn't want the server involved...why are you calling submit?
[Edit]
#Paul S's comment/answer looks very helpful. But you might look at something like the jQuery PostMessage plugin if you need it to be cross browser compatible.
http://benalman.com/projects/jquery-postmessage-plugin/
You don't require a POST request to send data from one page to another. Simply use LocalStorage to do the trick. Just call a Javascript function on form submission. This may help:
HTML:
<form id="form1" action="target.htm" method="post">
<div>
USB No: <input name="usbnum" id="usbnum" type="text"/><br />
USB Code: <input name="usbcode" id="usbcode" type="text"/>
</div>
<button onclick="post_to_page()">Try it</button>
</form>
Javascript:
function post_to_page() {
localStorage.value = "Your content here";
window.location = "nextpage.html";
}
This will save the data locally and go to the next page. In the next page, simply call this function to retrieve the stored data:
function get_stored_data() {
alert(localStorage.value);
}
You can simply assign it to a div, textbox other Javascript variable.

JS Variable Passing Via URL

I am designing a webpage that loads images of a document into the webpage and then will relocate to a specific image (page) based on a variable passed from another page. The code is below. Right now, it does not look like the variable 'page' is being updated. The page will alert
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<!-- Javascripts -->
<script type="text/javascript">
var pageCount = 40; /*Total number of pages */
var p; /*Variable passed to go to a specific page*/
function pageLoad(){ /*Loads in the pages as images */
for( i = 1; i<= pageCount; i++){
if(i < 10){
i = "0"+i;
}
document.body.innerHTML += "<div class='page'><a id='page" + i +"'><img src='pages/PI_Page_"+ i +".png' /></a></div>";
if( i == pageCount){
gotoPage(p);
}
}
}
function gotoPage(pageNum){ /* Moves webpage to target page of the PI */
window.location = ("#page" + pageNum);
alert(p);
}
function Test(){
window.open("./PI.html?p=15","new_pop");
}
</script>
</head>
<body onload="pageLoad()">
<div class="ExtBtn" onClick="Test()">
<img alt="Exit" src="design/exit_btn-02.png" />
</div>
</body>
</html>
The function TEST() was set up to allow me to have a link to re-open the page with p set to 15. The page opens, however, the function gotoPage() still alerts that p is undefined. Any ideas why that is?
Variables passed in the URL do not automatically become variables in JavaScript. You need to parse document.location and extract the value yourself.
p is never set a value anywhere so of course it will be undefined. You need to pull the value from the query string manually, JavaScript does not magically get the query string value for you.
Use the function here: How can I get query string values in JavaScript? to get the value.
Also why are you checking for the last index, set the go to call after the for loop.
Here is your code with the correct alert(p) working:
http://js.do/rsiqueira/read-param?p=15
I added a "function get_url_param" to parse url and read the value of "?p=15".

Categories

Resources