Want web page (js) file upload without form submission with servlet - javascript

I am attempting to write a web page that allows an upload of one or more files to a servlet without making a form submission.
I'm willing to use jQuery and/or Ajax; I do not want to use other third-party libraries.
I have a servlet that works WITH a form submission; I can make alterations to that if necessary to make it work without a form submission:
package ajaxdemo;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/* The Java file upload Servlet example */
#WebServlet(name = "FileUploadServlet", urlPatterns = { "/fileuploadservlet" })
#MultipartConfig
(
fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
maxFileSize = 1024 * 1024 * 10, // 10 MB
maxRequestSize = 1024 * 1024 * 100 // 100 MB
)
public class FileUploadServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Request-Method", "POST");
/* Receive file uploaded to the Servlet from the HTML5 form */
System.out.println("FileUploadServlet.doPost() invoked");
Part filePart = request.getPart("file");
String fileName = filePart.getSubmittedFileName();
for (Part part : request.getParts())
{
part.write("C:\\tmp\\" + fileName);
}
response.getWriter().print("The file uploaded sucessfully.");
response.getWriter().print("Filename: " + fileName + " saved in //tmp");
}
}
This works with the following input form:
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>File Upload Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "UploadFile.jsp" method = "post"
enctype = "multipart/form-data">
<input type = "file" name = "file" size = "50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
In trying to make it work without the form submission, I have the following page:
<html>
<head>
<!-- after https://www.w3schools.com/howto/howto_css_modals.asp -->
<style>
body{font-family: Arial, Helvetica, sans-serif; }
/* file Upload dialog (from w3schools howto_css_modals) */
.fileUploadDialogClass
{
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 */
}
/* "Modal Content" (from w3schools howto_css_modals) */
.fileUploadDialogClassContentClass
{
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
/* "The Close Button" (from w3schools howto_css_modals) */
.fileUploadDialogCloseButtonClass
{
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
/* (from w3schools howto_css_modals) */
.fileUploadDialogCloseButtonClass:hover,
.fileUploadDialogCloseButtonClass:focus
{
color: #000;
text-decoration: none;
cursor: pointer;
}
#upperLeft { background-color: lightgreen; border: 3px solid; }
#licenseeCityState {background-color: lightblue; }
#buttonDiv button { width: 100%; }
#mainTable { width: 100%; }
#mainTable { border: 1px solid; }
</style>
</head>
<body>
<script src="http://code.jquery.com/jquery-3.6.0.js"></script>
<!-- file upload popup dialog -->
<div id="fileUploadDialog" class="fileUploadDialogClass">
<div class="fileUploadDialogClassContentClass">
<span class="fileUploadDialogCloseButtonClass">×</span> <!-- 'times' is an 'x' for urh corner -->
<P>Select a file, then upload it to be read</P>
<br><input type="file" id="fileUploadChooserButton">
<br><button id="fileUploadButton">Upload</button>
</div>
</div>
<table>
<tr>
<td>
<div id='buttonDiv'>
<table id='buttonTable'>
<tr><td><button id='openButton'>Open File</button></td></tr>
<tr><td><button id='closeButton'>Close</button></td></tr>
</table>
</div>
</td>
<td style="vertical-align: top">
<div id='lowerRight'>
<table id='mainTable'>
<tr><td><div id="idString">xxx</div></td></tr>
</table>
</div>
</td>
</tr>
</table>
<script>
document.getElementById("idString").innerText = "xyz2"; // used to keep track of which version is displayed.
var fileUploadDialog = document.getElementById("fileUploadDialog");
var fileUploadDialogDisplayButton = document.getElementById("openButton");
var fileUploadDialogCloseButton = document.getElementsByClassName("fileUploadDialogCloseButtonClass")[0];
var fileUploadButton = document.getElementById("fileUploadButton");
//fileUploadButton.onclick = uploadFile();
fileUploadDialogDisplayButton.onclick = function() { fileUploadDialog.style.display = "block"; }
fileUploadDialogCloseButton.onclick = function() { fileUploadDialog.style.display = "none"; }
//async function uploadFile()
fileUploadButton.onclick = function()
{
console.log("uploadFile() invoked");
let formData = new FormData();
var fileUploadChooserButton = document.getElementById("fileUploadChooserButton");
var files = fileUploadChooserButton.files;
formData.append(files.name, files[0], files[0].name || "no filename")
;
console.log("about to await fetch");
// await fetch('http://localhost:8080/AjaxWithJSP/fileuploadservlet', { method: "POST", body: formData });
const xmlRequest = new XMLHttpRequest();
xmlRequest.onload = () =>
{
alert(xmlRequest.status + " reported as onload status");
};
//http://localhost:8080/AjaxWithJSP/LittleTable.html
xmlRequest.open('POST', 'http://localhost:8080/AjaxWithJSP/fileuploadservlet', true);
xmlRequest.setRequestHeader("Content-type", "multipart/form-data");
xmlRequest.send(formData);
}
window.onclick = function(event) { if(event.target == fileUploadDialog) { fileUploadDialog.style.display = "none"; } }
</script>
</body>
</html>
This produces an error message from the server (in the eclipse console) saying that no multipart boundary is found.
If I comment out the JavaScript line setting the request header, the error message is that filePart is null, so getSubmittedFileName() can't be called on it.
I found another explanation of doing it that involved await fetch(...) instead of xmlRequest.send(...); I have it commented out above. I couldn't make it work either.
Eventually, I want to allow the user to upload multiple files, and return a JSON structure with which I'll display a table. But I haven't figured out how to get the first file uploaded yet.

xmlRequest.setRequestHeader("Content-type", "multipart/form-data");
The multipart/form-data has a mandatory parameter describing the boundary that appears between each of the multiple parts.
Under normal circumstances, xhr or fetch will generate the whole Content-Type header, including the boundary parameter from the FormData object.
Here, you've overridden the Content-type and set it to multipart/form-data without a boundary.
Just don't do that.

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);

Add Show Dialog custom html to Google Slides Script

I'm trying to make this dialog popup for the duration of the execution of the AddConclusionSlide function, but I get the exception: "TypeError: Cannot find function show in object Presentation." Is there an alternative to "show" for Google Slides Script (This works perfectly in google docs)?
function AddConclusionSlide() {
htmlApp("","");
var srcId = "1Ar9GnT8xPI3ZYum9uko_2yTm9LOp7YX3mzLCn3hDjuc";
var srcPage = 6;
var srcSlide = SlidesApp.openById(srcId);
var dstSlide = SlidesApp.getActivePresentation();
var copySlide = srcSlide.getSlides()[srcPage - 1];
dstSlide.appendSlide(copySlide);
Utilities.sleep(3000); // change this value to show the "Running script, please wait.." HTML window for longer time.
htmlApp("Finished!","");
Utilities.sleep(3000); // change this value to show the "Finished! This window will close automatically. HTML window for longer time.
htmlApp("","close"); // Automatically closes the HTML window.
}
function htmlApp (status,close) {
var ss = SlidesApp.getActivePresentation();
var htmlApp = HtmlService.createTemplateFromFile("html");
htmlApp.data = status;
htmlApp.close = close;
ss.show(htmlApp.evaluate()
.setWidth(300)
.setHeight(200));
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
img {
display: block;
margin-left: auto;
margin-right: auto;
width: 25%;
}
.gap-10 {
width: 100%;
height: 20px;
}
.gap-20 {
width: 100%;
height: 40px;
}
.gap-30 {
width: 100%;
height: 60px;
}
</style>
</head>
<body>
<div class="container">
<div>
<p align="justify" style="font-family:helvetica,garamond,serif;font-size:12px;font-style:regular;" class="light">
Function is running... This could take a while. It's a lot of data...</p>
</div>
<p id="status">(innerHTML).</p>
<div id="imageico"></div>
<script>
var imageContainer = document.getElementById("imageico");
if (<?= data ?> != "Finished!"){
document.getElementById("status").innerHTML = "";
} else {
document.getElementById("status").innerHTML = "";
}
if (<?= close ?> == "close"){
google.script.host.close();
}
</script>
</body>
</html>
Unlike Spreadsheet object, Slide object doesn't have a show method. So, class ui needs to be used:
SlidesApp.getUi().showModalDialog(htmlApp.evaluate()
.setWidth(300)
.setHeight(200), "My App")

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.

How to create a thumbnail from image with close button

Here is my code:
https://codepen.io/manuchadha/pen/PBKYBJ
I have created a form. I want to be able to upload an image using the file upload input. When an image is selected, I want to show a thumbnail of the image just below the file selector box and also show a close (x) sign on the top-right corner of the image which could be used to delete the image. But I am unable to create it. What am I doing wrong?
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<base href="">
<title>Example</title>
<!--meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'"-->
<link rel="stylesheet" media="screen" href="fiddle.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="fiddle.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
</head>
<body>
<div id="form-div" class="body__div--background"> <!-- takes the complete width/height of content section -->
<!-- The novalidate attribute in the <form> element prevents the browser from attempting native HTML validations.
validation will be done using Angular's Validators which come with FormGroups and FormControls-->
<form id="new-question-form" class="practice-question-form" [formGroup]="practiceQuestionForm" (ngSubmit)="addPracticeQuestion()" novalidate>
<!-- label and small in same line. select in a new line, thus enclosed select in a div-->
<div class="form-group">
<div class="form-group">
<label for="file-upload" class="control-label required">Upload files</label>
<div class="custom-file" id="file-upload" lang="es">
<input type="file" class="custom-file-input" id="question-file-upload" onchange="handleFileSelect()">
<label class="custom-file-label" for="question-file-upload">
Select file...
</label>
</div>
</div>
<button type="submit" id="submit-practice-question-button" class="content-div__button--blue"> Submit! </button>
</form>
<div id="imageContainer">
</div>
</div>
</div>
</body>
CSS
body{
margin:0px;
}
.body__div--background {
background: linear-gradient(45deg,#33b1f8 37%,#6e90f6 100%); /*syntax linear-gradient(direction, color1 limit, color2 limit)*/
color:#555555;
font-family: Helvetica;
line-height:1.5;
font-size: 11px;
letter-spacing: 0.25px;
}
#submit-practice-question-button{
display:block;
}
#imageContainer{
display:inline-block;
border: 1px solid black;
}
.close {
top:0;
right:80; /*match the width of the image*/
position: relative;
opacity: 0.3;
}
.close:hover {
opacity: 1;
}
.close:before, .close:after {
position: relative;
left: 15px;
content: ' ';
height: 33px;
width: 2px;
background-color: #333;
}
.close:before {
transform: rotate(45deg);
}
.close:after {
transform: rotate(-45deg);
}
JS
/*handler for file upload*/
function handleFileSelect(){
console.log("got file upload event:");
/*
FileList object is the object returned as a result of a user selecting files using the <input> element,
from a drag and drop operation's DataTransfer object, or from the mozGetAsFile() API on an HTMLCanvasElement.
*/
var files = document.getElementById('question-file-upload').files;//event.target.files;
console.log("files selected:"+files+", total selected: "+files.length);
for(var i=0;i<files.length;i++)
{
console.log("files name:"+files[i].name)
console.log("files object:"+files[i])
}
//working with only 1 file at the moment
var file = files[0];
if (files && file) {
/*
The FileReader object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer,
using File or Blob objects to specify the file or data to read.
*/
var reader = new FileReader();
/*bind onload event of FileReader to _handleReaderLoaded
onload is a handler for the load event. This event is triggered by FileReader each time the reading operation is successfully completed.
*/
reader.onload =this._handleReaderLoaded.bind(this);
reader.readAsBinaryString(file);
}
}
function _handleReaderLoaded(readerEvt) {
var binaryString = readerEvt.target.result;
var base64textString= btoa(binaryString);
console.log(btoa(binaryString));
var src = "data:image/png;base64,";
src += base64textString;
var newImage = document.createElement('img');
newImage.src = src;
newImage.width = newImage.height = "80";
var closeButtonLink = document.createElement('a');
closeButtonLink.setAttribute('href',"#");
closeButtonLink.classList.add("close");
document.querySelector('#imageContainer').appendChild = newImage;
document.querySelector('#imageContainer').appendChild = closeButtonLink;
}
appendChild is a method, not a property.
For example instead of node.appendChild = newImage; it should be node.appendChild(newImage);
Also you needed to add the "X" in your anchor tag. I included that in the example below.
One more thing I did a small performance upgrade too where you save the reference to the query in a variable so you don't need to query the DOM twice.
var closeButtonLink = document.createElement('a');
closeButtonLink.textContent = "X";
closeButtonLink.setAttribute('href', "#");
closeButtonLink.classList.add("close");
// use a var here to only query once for imageContainer
var imgc = document.querySelector('#imageContainer');
imgc.appendChild(newImage);
imgc.appendChild(closeButtonLink);

Detecting content loaded on ajax div

I am using the ajaxpage function provided by the code on Dynamic Drive (http://www.dynamicdrive.com/dynamicindex17/ajaxcontent.htm).
I am trying to make the original page that sent the ajax content request to the div to detect once the div is loaded.
This is what I have tried:
A lot of research points to this
functionality in jQuery. I do not wish to use jQuery at all in this
project.
Including script in the loaded content. This doesn't work
and I believe it's due to limitations of this functionality.
I have
tried monitoring different states of the div, however nothing seems
to change.
All I really need is a way to call a function on the main page once the div content is loaded.
Modify ajaxpage function , add another parameter for a callback function, call your function within onreadystatechange. but I recommend you to use jQuery instead.
UPDATE:
Here's what I did. I added new a parameter called callback to your function ajaxpage , when you fire the ajax event onreadystatechange if I we get a true value from loadpage we excecute the callback and to identify which page or content was I'm adding the *page_request* and containerid arguments. Now you can add that callback function to your ajaxpage function in this case I did it with the function called myCallbackFunction.
I don't recommend you this approach there a better ways and best practices, if you're learning avoid this it seems out of date.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Ajax Rotating Includes Script</title>
<script type="text/javascript">
/***********************************************
* Dynamic Ajax Content- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice MUST stay intact for legal use
* Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
***********************************************/
var loadedobjects = ""
var rootdomain = "http://" + window.location.hostname
function ajaxpage(url, containerid, callback) {
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject) { // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
page_request = new ActiveXObject("Microsoft.XMLHTTP")
} catch (e) {}
}
} else
return false
page_request.onreadystatechange = function () {
if (loadpage(page_request, containerid)) {
if (callback)
callback(page_request, containerid);
}
}
page_request.open('GET', url, true)
page_request.send(null)
}
function loadpage(page_request, containerid) {
if (page_request.readyState == 4 && (page_request.status == 200 || window.location.href.indexOf("http") == -1)) {
document.getElementById(containerid).innerHTML = page_request.responseText
return true;
}
return false;
}
function loadobjs() {
if (!document.getElementById)
return
for (i = 0; i < arguments.length; i++) {
var file = arguments[i]
var fileref = ""
if (loadedobjects.indexOf(file) == -1) { //Check to see if this object has not already been added to page before proceeding
if (file.indexOf(".js") != -1) { //If object is a js file
fileref = document.createElement('script')
fileref.setAttribute("type", "text/javascript");
fileref.setAttribute("src", file);
} else if (file.indexOf(".css") != -1) { //If object is a css file
fileref = document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref != "") {
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects += file + " " //Remember this object as being already added to page
}
}
}
function myCallbackFunction(page_request,containerid) {
// Do your stuff here
console.log("page_request", page_request);
console.log("container id", containerid);
}
</script>
<style type="text/css">
#leftcolumn{
float:left;
width:150px;
height: 400px;
border: 3px solid black;
padding: 5px;
padding-left: 8px;
}
#leftcolumn a{
padding: 3px 1px;
display: block;
width: 100%;
text-decoration: none;
font-weight: bold;
border-bottom: 1px solid gray;
}
#leftcolumn a:hover{
background-color: #FFFF80;
}
#rightcolumn{
float:left;
width:550px;
min-height: 400px;
border: 3px solid black;
margin-left: 10px;
padding: 5px;
padding-bottom: 8px;
}
* html #rightcolumn{ /*IE only style*/
height: 400px;
}
</style>
</head>
<body>
<div id="leftcolumn">
Porsche Page
Ferrari Page
Aston Martin Page
<div style="margin-top: 2em">Load CSS & JS files</div>
Load "style.css" and "tooltip.js"
</div>
<div id="rightcolumn"><h3>Choose a page to load.</h3></div>
<div style="clear: left; margin-bottom: 1em"></div>
</body>
</html>

Categories