Apps Script Template HTML Breaks on Success Handler - javascript

Searched, but wasn't able to find any similar problems or solutions.
I have some templated HTML which builds a form based on data from a spreadsheet, as I have a variable number of dropdowns and options in those dropdowns.
On click of submit I want to display a spinning gif to the user, so they know it is processing.
If the backend code in code.gs passes the input through all the tests I want to update a div with a success message, if any of the checks fail with an error message.
I've got this to work, before with the create .createHtmlOutputFromFile method, but now with .createTemplateFromFile it just wipes the whole page.
HTML template
<style type="text/css">
#import url(http://fonts.googleapis.com/css?family=Open+Sans:400,600,300);
#container{
padding-left:10px;
font-family: 'Open Sans', Arial, sans-serif;
}
#header{
width: 75%;
margin: 0 auto;
text-align: center;
margin-bottom:10px;
}
form{
text-align: center;
margin-top:10px;
}
#nameField{
width:400px;
margin-bottom:10px;
}
#reqIndic{
color:#FF0000;
}
select{
margin-top: 5px;
width:150px;
}
#submit{
margin-top:20px;
width:125px;
height:40px;
}
#confirmation{
width: 30%;
margin: 0 auto;
min-height:60px;
border-radius: 5px;
}
#padding{
width: 30%;
margin: 0 auto;
min-height:60px;
border-radius: 5px;
}
</style>
<div id="container">
<div id="header">
<h2>Cheltenham Classic</h2>
</div>
<br>
<form name="projectsForm">
<span id="reqIndic">*</span>
<span> Name</span>
<input id="nameField" type="text" name="name" required>
<br>
<? for (var race in races) { ?>
<span><?= race ?></span>
<select>
<? for (var i = 0; i < races[race].length; i++) { ?>
<option value="<?= races[race][i] ?>"><?= races[race][i] ?></option>
<? } ?>
</select>
<br>
<? } ?>
<br>
<input id="submit" type="submit" value="Submit Form" onclick="google.script.run
.withSuccessHandler(updateDiv)
.onEvent(this.parentNode);spinner()">
</form>
</div>
<div id="confirmation" style ="text-align:center"></div>
<div id="padding" style ="text-align:center"></div>
<script type="text/javascript">
function updateDiv(returnValue){
alert('debug');
var div = document.getElementById('confirmation');
if(returnValue == false){
var errStr = '<p>ERROR: Please check your rankings for blank fields or multiple entries of the same project and re-submit your rankings</p>';
div.innerHTML = errStr;
}
else{
div.innerHTML = '<p>Success! Your results were submitted successfully</p>';
}
}
function spinner(){
var div = document.getElementById('confirmation');
div.innerHTML = '<img src="http://loadinggif.com/images/image-selection/32.gif">'
}
</script>
Back end code
I've cut the onEvent function right down to just returning an object with a key value pair without making any checks.
The updateDiv function runs and the alert shows then the entire page is wiped.
function doGet(){
var raceForm = HtmlService.createTemplateFromFile('RaceForm');
raceForm.races = getRaces();
return raceForm.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
function onEvent(e){
return {'valid': true};
}
function getRaces(){
var url = //spreadsheet url
var wb = SpreadsheetApp.openByUrl(url);
var ws = wb.getSheetByName('Races Log');
var racesObj = {};
var wsValues = ws.getDataRange().getValues();
for(var i = 0; i <wsValues.length;i++){
var race = wsValues[i][0];
racesObj[race] = [];
racesObj[race].push('0');
for(var j = 1; j<wsValues[i].length;j++){
racesObj[race].push(wsValues[i][j]);
}
}
return racesObj;
}
Any help much appreciated.

If I hard code the racesObj object:
var racesObj = {one:["one","two"], two:["one", "two"], "races":["belmont", "kentucky"]};
The page looks like this: (Using the template)
If I click the submit button, I get this:

Related

Creating new object instances and pushing them to an array in plain Javascript [duplicate]

This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 2 years ago.
I'm trying to create a form that when submitted, creates a new object with the input values, and then stores that object in an array.
For some reason, the array is "resetting" and not saving the objects.
let myLibrary = []
function Book(title,author,pages,read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
myLibrary.push(this)
}
function checkForm(){
let name = document.querySelector('input[name="title"]').value
let author = document.querySelector('input[name="author"]').value
let pages = document.querySelector('input[name="pages"]').value
let read = document.querySelector('input[name="read"]').checked
new Book(name,author,pages,read)
document.getElementById('library').innerText = JSON.stringify(myLibrary)
}
const submit = document.getElementById('btn1')
submit.addEventListener("click",checkForm);
<input name='title' />
<input name='author' />
<input name='pages' />
<input name='read' />
<button id='btn1'>Click me! </button>
<div >Library:</div>
<div id='library'></div>
You are listening for a click event on the submit button, however the submit button also submits the form. Forms will naturally cause a refresh if the default "submit" event is not prevented.
Instead you could listen to your forms submit event and prevent it:
// Query select the form and
form.addEventListener('submit', function(e){
e.preventDefault();
checkForm();
});
As you have a form in your html, you'll have to prevent its default submission event which results in a reload of the page with preventDefault(). You could, for example, change your checkForm() and add the e.preventDefault() there to prevent the form from being submitted.
let myLibrary = []
function Book(title, author, pages, read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
}
function addtoLibrary(title, author, pages, read) {
let book = new Book(title, author, pages, read)
myLibrary.push(book)
}
let table = document.querySelector(".table");
myLibrary.forEach(function(e) {
table.innerHTML += `<tr><td>${e.title}</td>
<td>${e.author}</td>
<td>${e.pages}</td>
<td>${e.read}</td>
</tr>
`
});
// Selectors
let add = document.querySelector("#add")
let submit = document.querySelector("#submit")
function checkForm(e) {
e.preventDefault(); // prevent the form from being submitted
let name = document.querySelector('input[name="title"]').value
let author = document.querySelector('input[name="author"]').value
let pages = document.querySelector('input[name="pages"]').value
let read = document.querySelector('input[name="read"]').checked
addtoLibrary(name, author, pages, read)
console.log(myLibrary);
}
submit.addEventListener("click", checkForm);
html,
body {
height: 100%;
}
* {
font-family: Graphik Regular;
}
ul {
list-style-type: none;
}
table,
th,
td {
border-collapse: collapse;
text-align: left;
border: 1px solid black;
}
table {
width: 100%;
}
td,
th {
height: 50px;
padding: 10px;
width: 200px;
min-width: 100px;
}
th {
background-color: gray;
margin-bottom: 50px;
}
.headers {
margin-bottom: 5px;
}
button {
background-color: #4CAF50;
/* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
margin-top: 30px;
}
.pop-container {
text-align: center;
/* display: none;*/
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
}
form {
background-color: gray;
}
input {
font-size: 20px;
width: 300px;
margin-bottom: 5px;
}
<!DOCTYPE html>
<meta charset="UTF-8">
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</stylesheet>
<script type="text/javascript" src="http://livejs.com/live.js"></script>
</head>
<body>
<div class="pop-container">
<form id="bookquery">
<input type="text" name="title" id="title" placeholder="Title"></br>
<input type="text" name="author" placeholder="Author"></br>
<input type="text" name="pages" placeholder="Pages"></br>
<p>Have you read it?<input type="checkbox" placeholder="Title" name="read"></p>
</br>
<button id="submit">Submit</button>
</form>
</div>
<table class="headers">
<th>Title</th>
<th>Author</th>
<th>Pages</th>
<th>Read</th>
</table>
<table class="table tstyle">
</table>
<button id="add">Add new book</button>
<script src="script.js"></script>
</body>
</html>
function checkForm(e) {
e.preventDefault(); // prevent the form from being submitted
let name = document.querySelector('input[name="title"]').value
let author = document.querySelector('input[name="author"]').value
let pages = document.querySelector('input[name="pages"]').value
let read = document.querySelector('input[name="read"]').checked
addtoLibrary(name, author, pages, read)
}
The above answers didn't quite work for me so here is a simplified, fully working example. As a general guide to getting things like this to work I always try to simplify as much as possible.
index.html
<html>
<header></header>
<body>
<div>
<form id="myForm">
<label for="title">title:</label><br>
<input type="text" id="title" name="title" value="title"><br>
<button id="submit">Submit</button>
</form>
</div>
<script type="text/javascript" src="functions.js"></script>
</body>
</html>
functions.html
let myLibrary = [];
function Book(title) {
this.title = title;
myLibrary.push(this);
}
function checkForm(){
let title = document.querySelector('input[name="title"]').value;
new Book(title);
myLibrary.forEach(function(element) {
console.log(element);
});
}
document.getElementById("myForm").addEventListener(
'submit',
function(e) {
e.preventDefault();
checkForm();
}
);
I'll leave it to you to add back in the other fields on the Book object.
I am not sure because I've tried to illustrate that your code actually stores the object. It's either that your form refreshes the page... that might be the cause but as far as the code you've provided is concerned, everything works as expected.
let myLibrary = []
function Book(title,author,pages,read) {
this.title = title
this.author = author
this.pages = pages
this.read = read
myLibrary.push(this)
}
function checkForm(name,author,pages,read)
{
new Book(name,author,pages,read)
}
checkForm("Chris","Jerry","56","65");
checkForm("Sean","John","56","65");
// Both Objects are still stored...
console.log(myLibrary);

Modal pops up after Ajax call completes instead of before or during

I am trying to get a modal popup to show "Please Wait" while an Ajax call is being made. The pop up occurs only after the call completes.
When I click my web link, everything is working, except the modal popup that is supposed to say "Please Wait" flashes for a split second AFTER the delay that the user is supposed to be asked to wait thru. That is, the modal pops up AFTER the Ajax call is completed instead of before.
When the page loads, it calls AjaxInitialUpdate. This works fine.
The issue is when you click the button that calls AjaxChangePassword.
The function is supposed to pull up a modal, then contact the web server, before finally removing the model and calling the AjaxInitialUpdate function to refresh the whole screen.
The issue is that the AjaxChangePassword modal doesn't pop up until the web query completes (by which time, there is no point in telling the user -- Please Wait).
Now, I am totally self-taught here, so I may be calling things by the wrong name or terms. I welcome any ideas to make it run better, but please be detailed, I'm still very novice in Java.
Also, the last time I did any kind of HTML programming was before Style sheets were the way to go, so I'm kind of having to learn them as well (and refresh on all the rest, so please explain any answer in detail).
Lastly, the server side of this is written in Powershell and is single threaded so I am trying to put as much in the HTML file as possible instead of calling secondary files, like style sheets and images.
<!DOCTYPE html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body {font-family: Arial, Helvetica, sans-serif;}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
/* Believe these are not needed.
Imported from web site that I copied the code from.
padding: 8px 8px;
outline: none;
border: none;
border-radius: 115px;
box-shadow: 0 3px #999; */
}
/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 70%;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
#IndividualSystem {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border: 1;
}
#IndividualSystem td, #IndividualSystem th {
text-align: left;
padding: 8px;
color: black
border: 1px solid black;
}
#IndividualSystem tr {
padding-top: 12px;
padding-bottom: 12px;
text-align: left;
background-color: #eeeeee;
}
.tab { margin-left: 40px; }
.button {
display: inline-block;
padding: 8px 8px;
font-size: 12px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #4CAF50;
border: none;
border-radius: 15px;
box-shadow: 0 3px #999;
}
.button:hover {background-color: #3e8e41}
.button:active {
background-color: #3e8e41;
box-shadow: 1 5px #666;
transform: translateY(4px);
}
.button2 {
display: inline-block;
padding: 8px 8px;
font-size: 12px;
cursor: pointer;
text-align: center;
text-decoration: none;
outline: none;
color: #fff;
background-color: #000080;
border: none;
border-radius: 15px;
box-shadow: 0 3px #999;
}
.button2:hover {background-color: #df330e}
.button2:active {
background-color: #FD2E02;
box-shadow: 1 5px #666;
transform: translateY(4px);
}
#IndividualSystem {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
width: 100%;
border: 1;
}
</style>
<Title>Cyber Track</title>
</head>
<body>
<table>
<tr>
<td>blah</td>
<td><h1>Systems and Passwords</H1>
<h3>Information within this page is considered confidential.</h3>
</td></tr>
</table>
<hr>
<input type="hidden" id="Leftlink" name="Leftlink" value="0">
<input type="hidden" id="Rightlink" name="Rightlink" value="0">
<input type="hidden" id="serverID" name="serverID" value="server8\admin-server8">
<input type="hidden" id="count" name="count" value="10"> <!--- Number of servers per page on server list //-->
<!-- The Modals #1 -->
<div id="myModal1" class="modal">
<!-- Modal content -->
<div class="modal-content">
<h4><label id="ModalTextLine1">Loading content from server</label></h4>
</div>
</div>
<!-- The Modals #2 -->
<div id="myModal2" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close2">×</span>
How long do you need the password?
<form action='#'>
<select name="days">
<option value='1' >1 day or less</option>
<option value='7'>between 1 and 2 days</option>
<option value='7'>between 2 and 7 days</option>
<option value='30'>between 7 and 30 days</option>
<option value='365' selected>for up to a year.</option>
</select>
<br>
<input type="submit" value="Process Request">
</form>
</div>
</div>
<script>
// Get the modal
var modal2 = document.getElementById('myModal2');
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close2")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal2.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it (or actually, just hide it)
window.onclick = function(event) {
if (modal2.style.display != "none")
{
if (event.target == modal2) {
modal2.style.display = "none";
}
}
}
</script>
<!-- End Loaded from function -->
<table id="IndividualSystem"> <!-- IndividualSystem - to define needed style sheet //-->
<tr>
<td style="width: 215px;">Server</td>
<td style="width: 259px;"><label ID="DynServerName">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;">User ID</td>
<td style="width: 259px;"><label ID="DynAdminID">Loading</label></td>
</tr>
<tr>
<td colspan="2"><hr></td>
</tr>
<tr>
<td style="width: 215px;">Checked out status:</td>
<td style="width: 259px;"><label ID="DynLastCheckedout">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;" valign='top' >Last checked out by:</td>
<td style="width: 259px;" valign='top' ><label ID="DynLastCheckedBy">Loading...</label>
<button class="button" onclick="javascript:AjaxCheckOutPassword()" id="PassStatus">Loading</button> <!-- AjaxCheckOutPassword -->
</td>
</tr>
<tr>
<td valign='top' style="width: 215px;">Expected Check In Date:</td>
<td valign='top' style="width: 259px;"><label ID="DynExpectedBack">Loading</label></td>
</tr>
<tr>
<td style="width: 215px;">Date of last password change:</td>
<td style="width: 259px;"><label id="DynLastReset">Loading</label> <button class="button2" onclick="AjaxChangePassword()">Force Change Now!</button>
</td>
</tr>
<tr>
<th colspan="2">Notify:<br>
<table border="1" padding = "0" width=100%>
<tr>
<td width=200>On Use:</td><td><label id="DynEmailCheckOut">Loading</label></td>
</tr>
<tr>
<td width=200>On Checkin:</td><td><label id="DynEmailCheckIn">Loading</label></td>
</tr>
</table>
</th>
</tr>
<tr><td colspan="2">
<label ID="DynAccountPurpose"></label>
</td></tr>
</tbody>
</table>
<!-- Page Footer (if any) //-->
<!-- Page links left/up/right //-->
<table>
<tr><td width = 50>
<label id="Show-Left">
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(-1)" text='Prior Server'>
<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAEAAAAAAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAgABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD9+Wwp/wDrVzHxS+Kmk/B3wfda3rdz9lsbPZ5kvlvJ951QfKis3V1HA7074ofE/SPhD4RvNc1m5+x6fZ7PNl8t5Nu50ReFBJyzgcDv6Dj853k8Zf8ABW/4sgY/sv4d6T0X9zPjzIfX9xNzPae/X+6Ob9naPtJ7GXM5Plgfod8H/jHoXxw8FW3iDw7c/btPvt4WTy5I87JHj6SKp+8jfwj8etddvHp+hrm/hb8L9H+EnhO30PQ7f7JZWe7am93xvdnPLsx6sT1P8q6QcDjbjt8prGPdm0rHjv7Yf7JOj/tW/DuTS9Q/0e6jx5M+Hfyv3sTt8qyIDkRAc9O1fH/7GP7T+t/sN+P4/hD8TB5OnQ5+yXX7t/s+Y5rt/kt45C2WmiHMnGeOMgfpEWJb73H0614v+2N+x1oP7WfgiTT9SBt7+HBtrr94/lZkhZvkWRAciEDn8OldCqc0fZzMJU+WXNA9hsb9NQtVlhfdG2drYIzg4PWp8r/drzb9lv4I3fwH+EWn+HNQ1X+2JrPzM3H2YW+7dNLJ90MwGBIB949Pwr0kx8/d/SsIO2jOjRn/2Q==' alt='go to prior server' height='26' width='32'>
</a>
</label>
</td>
<td>
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(0)" text='Next server'>Return to main list</a>
</td>
<td width = "50">
<label id="Show-Right">
<a class='w3-left w3-btn' href='#' onclick="AjaxNavigate(1)" text='Next server'>
<img src='data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAAgABoDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD97dc1U6Zp000cfnPHt+Tdt3ZIHX8a+Z/2Sv8AgpDpfx98c3/hjWNP/wCEf16Dy/Kt/Pe78zMcsp+ZYVQYSMHk/wAXqK+oihPT8DXx7/wUM/4J8r8Wo4/GXg5fsfi7T85XPmfat/2eH/lrMsabYkf+E5z64NEHGM+WezFUTcbw3PsMgtjj6nNO8pfSvjn/AIJv/wDBRD/hoLTj4b8UDyPFFr99s7vtG43Eg4jhWNdsca9+frmvsPa3/PX/AMdrSdKUHZkQqxmtCPULyK1tXef5YVxuPJ7+3PWvzt/a4/a28S/tm/Ek/Cz4V/vrOX/j7u/3S+ZiKK6T5LmOMjBhlHD+57A/ofqenQ6hbPFP80BxuXkdwRyOetef/Aj9lXwh+zpHer4a077AL7y/NP2iaXds34/1kj4/1jdPWsYqLneey/E0nJqP7vcwv2Ov2OdD/ZM+H/8AZunjzr64/wCPy7zIv2jbJMyfI0jhdolI4PPU+3su5fX9KAdwyRgntmn7hWs6spvmkZwpRjsf/9k=' alt='go to prior server' height='26' width='32'>
</a>
</label>
</td>
</tr></table>
<!-- End Page links left/up/right //-->
<!-- Dynamic JAVA Script Section //-->
<script>
// disable our NAV pointers till later where we may re-enable them.
document.getElementById('Show-Right').style.display = 'none';
document.getElementById('Show-Left').style.display = 'none';
//
// This is the specific function that I need help with.
// Why does this modal pop up only after the actual query is done?
//
function AjaxChangePassword(){
document.getElementById('myModal1').style.display = "block";
document.getElementById('myModal2').style.display = "none"; // Make sure its not poped up..
// we need to set item on the modal to explain what we are doing...
document.getElementById("ModalTextLine1").innerHTML="Processing password change request. Please Wait"
var xhr = "";
var xhr = new XMLHttpRequest();
// server will check if values are valid..
var Server = document.getElementById("DynServerName").innerHTML;
var AdminID = document.getElementById("DynAdminID").innerHTML;
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=change&server=' + Server + '/' + AdminID+'&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Comment Response onpassword change.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response);
console.log("Report password changed.");
AjaxInitialUpdate() // password changed, lets refresh.
};
};
};
xhr.send(null);
document.getElementById('myModal1').style.display = "none";
};
// Navigate left and right..
function AjaxNavigate(link)
{
xx = document.getElementById('Leftlink').value
xx = document.getElementById('Rightlink').value
if (link == 0)
{
// Back to the main page. Get the values that make who we are -- servername and count.
var count = document.getElementById('count').value;
var CurrentSystem = document.getElementById('serverID').value;
var x = '/CyberPass3/?command=homepage&server=' + CurrentSystem + '&count='+ count + '&NoCache=' + ((new Date()).getTime());
location.replace('/CyberPass3/?command=homepage&server=' + CurrentSystem + '&count='+ count + '&NoCache=' + ((new Date()).getTime()));
}
else
{
if (link == 1)
{
document.getElementById('serverID').value = document.getElementById('Rightlink').value
} else {
document.getElementById('serverID').value = document.getElementById('Leftlink').value
}
// we've moved left or right. Lets update.
AjaxInitialUpdate()
}
}
function AjaxCheckOutPassword() {
console.log("Checkout Code not yet written");
};
function AjaxInitialUpdate() {
var xhr = ""
var xhr = new XMLHttpRequest();
var count = document.getElementById('count').value;
var link = document.getElementById('serverID').value
document.getElementById('myModal1').style.display = "block"; // show we are updating everything..
document.getElementById('myModal2').style.display = "none"; // should already be hidden, but lets make sure..
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=refresh&server=' + link + '&count=' + count + '&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Response.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
WebFields = xhr.responseText.split("|");
document.getElementById("DynServerName").innerHTML = WebFields[0];
document.getElementById("DynAdminID").innerHTML = WebFields[1];
document.getElementById("DynLastCheckedout").innerHTML = WebFields[2];
document.getElementById("DynLastCheckedBy").innerHTML = WebFields[3];
document.getElementById("DynExpectedBack").innerHTML = WebFields[4];
document.getElementById("DynLastReset").innerHTML = WebFields[5];
document.getElementById("PassStatus").innerHTML = WebFields[6];
document.getElementById("DynEmailCheckIn").innerHTML = WebFields[7];
document.getElementById("DynEmailCheckOut").innerHTML = WebFields[8];
// if no comment, don't even dispay the table cells.
if (WebFields[9].slice(0,1) == "{" && WebFields[9].slice(-1) == "}" && WebFields[9] != "{}" )
{
var res = WebFields[9].split("{");
var res = res[1].split("}")[0];
document.getElementById("DynAccountPurpose").innerHTML = "<tr><td style='width: 474px;' colspan='2'><p><b>Account Comments:</b></p><p class='tab'>" + res + "</p></td></tr>";
}
else
{
document.getElementById("DynAccountPurpose").innerHTML = "";
console.log("No Comment");
};
// lets populate the nav buttons..
if (WebFields[10] == '\\')
{
// hide go left
document.getElementById('Show-Left').style.display = 'none';
document.getElementById("Leftlink").value = "0/0"
}
else
{
//Enable go left
document.getElementById('Show-Left').style.display = 'block';
document.getElementById('Leftlink').value = WebFields[10];
};
// lets populate the nav buttons..
if (WebFields[11] == "\\")
{
// hide go right
document.getElementById('Show-Right').style.display = 'none';
document.getElementById("Rightlink").value = "0/0";
}
else
{
// Enable go right
document.getElementById('Show-Right').style.display = 'block';
document.getElementById("Rightlink").value = WebFields[11];
};
document.getElementById('myModal1').style.display = "none";
}
if (xhr.status === 403) {
console.log(xhr.response);
document.getElementById("PassStatus").innerHTML = 'Access Denied';
}
if (xhr.status === 404) {
console.log(xhr.response);
document.getElementById("PassStatus").innerHTML = 'Unable to load';
};
}
else
{
document.getElementById("PassStatus").innerHTML = "Failed";
};
};
xhr.send(null);
};
// Now, load the initial value..
window.onload = AjaxInitialUpdate();
</script>
When I call AjaxChangePassword(), I expected the modal to open BEFORE the query.
As it is now, if I stop the server after the page loads, but before this function is started, the modal never pops up, then once I start the server side back up, and I see the query come in and get answers, only then does it pop up, and then only for a split second.
What am I doing wrong in the way I am calling it?
As I reviewed your code and found that in the function AjaxChangePassword firstly you opened modal and then called ajax then closed modal the problem is that basically javascript executes synchronously but if there is ajax call then it executes asynchronously, so according to that your modal opens and then call ajax untill ajax is busy in getting response before that next line will be executed that line is for modal close and this happens in the fraction of ms so you don't see anything, And you said that after ajax call modal is showing because in AjaxChangePassword the call back method is AjaxInitialUpdate and also in this method you opened modal then closed but remember in this method you closed modal in the call back method so it appears for some time and you can see so according to me just remove
document.getElementById('myModal1').style.display = "none";
this line from AjaxChangePassword method below is corrected AjaxChangePassword function
function AjaxChangePassword(){
document.getElementById('myModal1').style.display = "block";
document.getElementById('myModal2').style.display = "none"; // Make sure its not poped up..
// we need to set item on the modal to explain what we are doing...
document.getElementById("ModalTextLine1").innerHTML="Processing password change request. Please Wait"
var xhr = "";
var xhr = new XMLHttpRequest();
// server will check if values are valid..
var Server = document.getElementById("DynServerName").innerHTML;
var AdminID = document.getElementById("DynAdminID").innerHTML;
xhr.open('GET', 'http://PSShellSrv.mydomain.local:80/CyberPass3/?command=update&sub=change&server=' + Server + '/' + AdminID+'&NoCache=' + ((new Date()).getTime()), true);
xhr.responseType = 'text';
xhr.onload = function () {
console.log('Initail Comment Response onpassword change.');
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
document.getElementById('myModal1').style.display = "none";
console.log(xhr.response);
console.log("Report password changed.");
AjaxInitialUpdate() // password changed, lets refresh.
};
};
};
xhr.send(null);
};
and check. I may be wrong but check it.

HTML JS form to div comments (temporary change)

I have seen many similar problems but when I try them they end up failing. It has gotten to the point where my code is totally messed up and I need some help both cleaning it up and fixing my issue. (using chrome)
So far I have tried selecting the value of the form and putting that into a div,
I have tried to use the button as just a link to start the script so that the page doesn't reset and also many other answers found on-line, none of them are helping so I am asking for a personalised help.
function on_comment_add() {
var main = document.getElementById("div1");
var add_user_name = document.createElement("div");
var add_user_comment = document.createElement("div");
add_user_name.setAttribute("id", "add_user_name");
add_user_comment.setAttribute("id", "add_user_comment");
<!-- var node = document.createTextNode("This is new."); -->
var node_1 = document.getElementById("user_name").value;
var node_2 = document.getElementById("user_comment").value;
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
var element = document.createElement("div");
element.setAttribute("id", "display_comment_div");
element.appendChild(add_user_name);
element.appendChild(add_user_comment);
main.appendChild(element);
main.innerHTML = element;
return false;
}
body {
background-color: lightGreen;
}
div.middle {
width: 80%;
margin-left: 10%;
background-color: #47e077;
height: 940px;
font-size: 10pt;
font-family: aubrey;
border: 3px solid gold;
}
.comments-form {
text-align: center;
}
#display_comment_div {
background: rgba(200, 54, 54, 0.1);
width: 80%;
margin-left: 9%;
border: 0.1px solid lightGreen;
border-radius: 25px;
}
#add_user_name {
width: 45%;
float: left;
}
#add_user_comment {
width: 45%;
display: inline-block;
float: right;
}
<div class="middle">
<div class="comments-form">
<form>
<label for="name" style="width:100px; display:inline-block;">Name</label>
<input id="user_name" type="text" placeholder="name goes here" style="width:300px; margin-left:5px;" />
<br><br>
<label for="comment" style="width:100px; display:inline-block;">Comment</label>
<textarea id="user_comment" placeholder="comment goes here" maxlength="150" style="width:300px;max-width:300px;"></textarea><br>
<button style="margin-left:310px;" onmousedown="return on_comment_add">Submit</button>
</form>
<div id="div1">
</div>
</div>
</div>
I guess what I am asking is if anyone can help me display the username and comment below the form but it seems tricky for me because I have gone through so many answers that don't work for me that I cannot think of any other ways to do it.
For clarification this code is not meant to keep the comments from the form nor is it meant to be a fully functioning site. I am just making slight modifications to some code so that I can hand it in as a college assignment.
Using onclick and pass the event inside:
<button style="margin-left:310px;" onclick="on_comment_add(event)">Submit</button>
And disable the default form submit action:
function on_comment_add(e) {
e.preventDefault()
var main = document.getElementById("div1");
var add_user_name = document.createElement("div");
var add_user_comment = document.createElement("div");
add_user_name.setAttribute("id", "add_user_name");
add_user_comment.setAttribute("id", "add_user_comment");
var node_1 = document.createElement("div");
node_1.innerHTML= document.getElementById("user_name").value;
var node_2 = document.createElement("div");
node_2.innerHTML = document.getElementById("user_comment").value;
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
var element = document.createElement("div");
element.setAttribute("id", "display_comment_div");
element.appendChild(add_user_name);
element.appendChild(add_user_comment);
main.appendChild(element);
return false;
}
Workable example: https://jsfiddle.net/kingychiu/z6gnqswn/
Change type to "button" to prevent automatical form sending and add parentheses to onmousedown expression:
<button type="button" style="margin-left:310px;" onmousedown="return on_comment_add()">Submit</button>
Then change this
add_user_name.appendChild(node_1);
add_user_comment.appendChild(node_2);
to this (since node_1, node_2 are values, not elements):
add_user_name.innerHTML = node_1;
add_user_comment.innerHTML = node_2;
And remove that line
main.innerHTML = element;
above
return false;
That should work.

Auto-Suggest Text Box

I found an example online that shows how to build a auto-suggest text field by using javascript and PHP. Originally I started out by building my on version of the example, but after many failed attempts in getting it to work, I decided to see if the example itself even worked. I copied and pasted the example, changing only the database connection and the information regarding the database table. To my surprise the example still doesn't work! In my database I have a a table called Device and in that table there are three columns, ID,Device_type, and Price. Right now I have one value in the table and it's Apple iPhone 6 in the Device_type column, so when the program is working correctly, it should start to auto suggest Apple iPhone 6 as soon as I type "A" into the text box. Unfortunately, that doesn't happen, a dropdown box appears, as it should, but the box is blank and doesn't show any suggestions.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>List Suggestion Example</title>
<style type="text/css">
<!--
div.suggestions {
-moz-box-sizing: border-box;
box-sizing: border-box;
border: 1px solid black;
text-align: left;
}
-->
</style>
<script type="text/javascript">
var nameArray = null;
</script>
</head>
<body onclick="document.getElementById('divSuggestions').style.visibility='hidden'">
<?php
mysql_connect("hostname", "username", "password") OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db('DeviceRecycling');
$query = 'SELECT Device_type FROM Device';
$result = mysql_query($query);
$counter = 0;
echo("<script type='text/javascript'>");
echo("this.nameArray = new Array();");
if($result) {
while($row = mysql_fetch_array($result)) {
echo("this.nameArray[" . $counter . "] = '" . $row['Device_type'] . "';");
$counter += 1;
}
}
echo("</script>");
?>
<!-- --------------------- Input Box --------------------- -->
<table border="0" cellpadding="0" width="50%" align="center">
<tbody align="center">
<tr align="center">
<td align="left">
<input type="text" id="txtSearch" name="txtSearch" value="" style="width: 50%; margin-top: 150px; background-color: purple; color: white; height: 50px; padding-left: 10px; padding-right: 5px; font-size: larger;" onkeyup="doSuggestionBox(this.value);" />
<input type="button" value="Google It!" name="btnGoogleIt" style="margin-top: 150px; background-color: purple; color: white; height: 50px; font-size: larger;" onclick="window.location='http://www.google.com/#hl=en&source=hp&q=' + document.getElementById('txtSearch').value" />
</td>
</tr>
<tr align="center">
<td align="left">
<div class="suggestions" id="divSuggestions" style="visibility: hidden; width: 50%; margin-top: -1px; background-color: purple; color: white; height: 250px; padding-left: 10px; padding-right: 5px; font-size: larger;" >
</div>
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function doSuggestionBox(text) { // function that takes the text box's inputted text as an argument
var input = text; // store inputed text as variable for later manipulation
// determine whether to display suggestion box or not
if (input == "") {
document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
} else {
document.getElementById('divSuggestions').style.visibility = 'visible'; // shows the suggestion box
doSuggestions(text);
}
}
function outClick() {
document.getElementById('divSuggestions').style.visibility = 'hidden';
}
function doSelection(text) {
var selection = text;
document.getElementById('divSuggestions').style.visibility = 'hidden'; // hides the suggestion box
document.getElementById("txtSearch").value = selection;
}
function changeBG(obj) {
element = document.getElementById(obj);
oldColor = element.style.backgroundColor;
if (oldColor == "purple" || oldColor == "") {
element.style.background = "white";
element.style.color = "purple";
element.style.cursor = "pointer";
} else {
element.style.background = "purple";
element.style.color = "white";
element.style.cursor = "default";
}
}
function doSuggestions(text) {
var input = text;
var inputLength = input.toString().length;
var code = "";
var counter = 0;
while(counter < this.nameArray.length) {
var x = this.nameArray[counter]; // avoids retyping this code a bunch of times
if(x.substr(0, inputLength).toLowerCase() == input.toLowerCase()) {
code += "<div id='" + x + "'onmouseover='changeBG(this.id);' onMouseOut='changeBG(this.id);' onclick='doSelection(this.innerHTML)'>" + x + "</div>";
}
counter += 1;
}
if(code == "") {
outClick();
}
document.getElementById('divSuggestions').innerHTML = code;
document.getElementById('divSuggestions').style.overflow='auto';
}
</script>
</body>
</html>
In my attempt to trouble shoot, I have discovered a few things. First off the connection string to the database is good, and that is not the problem. In an attempt to further check whether it was the database query that was causing issues, I have discovered that if I remove the echo("<script type='text/javascript'>") from the PHP portion of the code, that it will actually print Apple iPhone 6 at the top of the page, which tells me the query itself is actually working. Obviously though, by removing the javascript tag the program still doesn't work because it should only be displaying the results as you type something that matches what is in the database.
hi maybe you have a error on your code
this is a little example
for get the result and show
autocomplete.php
<?php
$connection = mysqli_connect("localhost","username","password","employee") or die("Error " . mysqli_error($connection));
//fetch department names from the department table
$sql = "select department_name from department";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = $row['department_name'];
}
echo json_encode($dname_list);
?>
for view and show the result
demo.php
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete Textbox Demo | PHP | jQuery</title>
<!-- load jquery ui css-->
<link href="path/to/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<!-- load jquery library -->
<script src="path/to/jquery-1.10.2.js"></script>
<!-- load jquery ui js file -->
<script src="path/to/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
var availableTags = <?php include('autocomplete.php'); ?>;
$("#department_name").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
</head>
<body>
<label>Department Name</label></br>
<input id="department_name" type="text" size="50" />
</body>
</html>
i preffer use jquery
donwload jquery
enter link description here
result

jQuery search bar only working one time per page

I am working on a page for pre-registration to events on my website. On this page, people need the ability to add names into as many slots as the event creator would like (so it needs to handle 3 person basketball teams and 50 person banquets). I have had a high quality facebook-like search bar made so that I can neatly search through the database and select the desired people. Sadly I have this search bar being created by a for loop that creates many different ID filled search bars but every one of them is left empty and the first search bar is the only one that is filled.
I found that it deals with the jQuery code at the top of my page. My question/issue is that I need this jQuery to work on multiple search bars on a single page. If anyone can help me accomplish this I'd be greatly appreciative.
The "top code" or JQuery code that pulls from the db successfully is:
$(function(){
$(".search").keyup(function()
{
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!='')
{
$.ajax({
type: "POST",
url: "../searchMyChap.php",
data: dataString,
cache: false,
success: function(html)
{
$("#divResult").html(html).show();
}
});
}return false;
});
jQuery("#divResult").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
$('#inputSearch').click(function(){
jQuery("#divResult").fadeIn();
});
});
</script>
<style type="text/css">
body{
font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
}
.contentArea{
width:600px;
margin:0 auto;
}
/*
#inputSearch
{
width:350px;
border:solid 1px #000;
padding:3px;
}
*/
#divResult
{
position:absolute;
width:545px;
display:none;
margin-top:-1px;
border:solid 1px #dedede;
border-top:0px;
overflow:hidden;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
-moz-border-bottom-right-radius: 6px;
-moz-border-bottom-left-radius: 6px;
box-shadow: 0px 0px 5px #999;
border-width: 3px 1px 1px;
border-style: solid;
border-color: #333 #DEDEDE #DEDEDE;
background-color: white;
}
.display_box
{
padding:4px; border-top:solid 1px #dedede;
font-size:12px; height:50px;
}
.display_box:hover
{
background:#0088cc;
//background:#3bb998;
color:#FFFFFF;
cursor:pointer;
}
The for-loop code that prints the search bars is as follows:
for($i = 0; $i < $looper; $i++)
{
echo'
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Member Name:</label>
<input type="text" class="form-control search" name="member'.$i.'" autocomplete="off" id="inputSearch" placeholder="Search...">
<div id="divResult" style="z-index:999; margin-top: 35px;" ></div>
</div>
</div>
</div>';
}
EDIT: Working JSFiddle
The first issue is that with each iteration of the for loop an element is created with id="divResult". An ID should be used once in the whole document. I have changed the for loop to produce an element with class="divResult" instead. If you use this change, remember that your CSS will need to be changed accordingly.
for ($i = 0; $i < $looper; $i++) {
echo '
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Member Name:</label>
<input type="text" class="form-control search" name="member'.$i.'" autocomplete="off" id="inputSearch" placeholder="Search...">
<div class="divResult" style="z-index:999; margin-top: 35px;"></div>
</div>
</div>
</div>';
}
Next we iterate over each .search element. Within each iteration we can find the corresponding 'result' element by using jQuery's next() function, which retrieves the immediately following sibling of an element. If the code is ever changed such that the 'results' element does not appear straight after the `.search' element, this will need changing.
$(function () {
$('.search').each(function(index) {
var $searchElement = $(this);
var $resultElement = $searchElement.next();
console.log(index, $searchElement, $resultElement);
$searchElement.on('keyup', function() {
var inputSearch = $searchElement.val();
var dataString = 'searchword=' + inputSearch;
if (inputSearch != '') {
$.ajax({
type: "POST",
url: "../searchMyChap.php",
data: dataString,
cache: false,
success: function (html) {
$resultElement.html(html).show();
}
});
}
return false;
});
$resultElement.on("click", function (e) {
var $clicked = $(this);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$searchElement.val(decoded);
});
$(document).on("click", function (e) {
var $clicked = $(e.target);
if (!$clicked.hasClass("search")) {
$resultElement.fadeOut();
}
});
$searchElement.on('click', function () {
console.log(index + ' clicked');
$resultElement.fadeIn();
});
});
});

Categories