I cant get my webpage to pull data from an xml file inside the same folder - html

I'm not well versed in javascript nor xml but i'm trying to create a webpage where i can search through products on an xml file by filtering them by an ID Code. I've tried many things but i don't get errors, just nothing happens when i click search. Any help on where i'm going wrong would be appreciated as honestly I have barely any idea what i'm doing.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vendor</title>
</head>
<body>
<input type="number" id="Code">
<button type="button" name="button" onclick="loadData()">Get Product</button>
<div id="results">
</div>
<script type="text/javascript">
async function loadData(){
var data = await fetch("product.xml")
var parsedData = await data.text()
var parser = new DOMParser();
var ProductDoc = parser.parseFromString(parsedData,"text/xml");
var results = ""
var CodeInput = parseInt(document.getElementById("Code").value)
var product = ProductDoc.getElementsByTagName("product")
for(var i = 0; i < product.length; i++){
var Category = Category[i].getElementsByTagName("Category")[0].childNodes[0].nodeValue
var Code = Code[i].getElementsByTagName("Code")[0].childNodes[0].nodeValue
var Name = Name[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue
var Description = Description[i].getElementsByTagName("Description")[0].childNodes[0].nodeValue
var Quantity = Quantity[i].getElementsByTagName("Quantity")[0].childNodes[0].nodeValue
var UnitPrice = UnitPrice[i].getElementsByTagName("Category")[0].childNodes[0].nodeValue
if(isNaN(CodeInput) || CodeInput == parseInt(Code)) {
results += "<div>"
+ "Category: " + Category
+ ", Code: " + Code
+ ", Name: " + Name
+ ", Description: " + Description
+ ", Quantity: " + Quantity
+ ", UnitPrice: " + UnitPrice
+ "</div><br/>"
}
}
document.getElementById("results").innerHTML = results
}
</script>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<main xmlns:product="index.html">
<product>
<product:Category>example</product:Category>
<product:Code>111-11</product:Code>
<product:Name>example</product:Name>
<product:Description>example</product:Description>
<product:Quantity>example</product:Quantity>
<product:UnitPrice>example</product:UnitPrice>
</product>
<product>
<product:Category>example</product:Category>
<product:Code>122-22</product:Code>
<product:Name>example</product:Name>
<product:Description>example</product:Description>
<product:Quantity>example</product:Quantity>
<product:UnitPrice>example</product:UnitPrice>
</product>
</main>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="index.html" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="Category" type="xs:string" />
<xs:element name="Code" type="xs:string" />
<xs:element name="Name" type="xs:string" />
<xs:element name="Description" type="xs:string" />
<xs:element name="Quantity" type="xs:string" />
<xs:element name="UnitPrice" type="xs:string" />
</xs:schema>

Since you are dealing with an xml document which contains namespaces, it safer to parse it using an xml parser with a namespace resolver. The following should get you close enough to what you are looking for:
let parser = new DOMParser(),
ProductDoc = parser.parseFromString(parsedData, "application/xml"),
evaluator = new XPathEvaluator(),
resolver = evaluator.createNSResolver(ProductDoc),
results = "",
products = ProductDoc.evaluate('//product', ProductDoc, resolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (let i = 0; i < products.snapshotLength; i++) {
let tags = ProductDoc.evaluate('.//product:*', products.snapshotItem(i), resolver, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
new_div = "<div>"
for (let i = 0; i < tags.snapshotLength; i++) {
new_div += `${tags.snapshotItem(i).localName}: ${tags.snapshotItem(i).textContent} <br/>`
}
results += `${new_div}</div><br/>`
}
document.getElementById("results").innerHTML = results

Related

Saving information in google sheets from my form

I try to save file on google drive and information in google sheets. But information in Sheets comes like Java.object.
Here is how it looks like in Code.gs :
var FOLDER_ID = '1jxBwrsz0JdBHcADpUUMespe';
var SHEET_ID = '1oJcKQ2RrtxxE1mn_CP-UAHefDxV7zg4';
function doPost(e) {
var data = Utilities.base64Decode(e.parameters.data);
var blob = Utilities.newBlob(data, e.parameters.mimetype, e.parameters.name);
var folder = DriveApp.getFolderById(FOLDER_ID);
var file = folder.createFile(blob);
folder.createFolder(name)
var res = [];
SpreadsheetApp.openById(SHEET_ID).getSheets()[0].appendRow([e.parameters.name, file.getUrl()].concat(res));
return ContentService.createTextOutput("Done.")
}
Here is how it looks like in the HTML file :
<form action="https://script.google.com/macros/s/AKfycbxkzg6ud1VyTI2W4gs-CRJRS3i3qLDXQIGevtyy/exec" id="form" method="post">
<div id="data"></div>
<div class="form-group">
<label for="name">Имя</label>
<input type="text" id='name' name="name" placeholder="Имя" />
</div>
<div class="form-group">
<label for="comment">Комм</label>
<input type="text" name="comment" placeholder="Комментарий" />
</div>
<input name="file" id="uploadfile" type="file">
<input id="submit" type="submit">
</form>
<script>
$('#uploadfile').on("change", function() {
var file = this.files[0];
var fr = new FileReader();
var name = $('#name').value;
fr.fileName = file.name
fr.onload = function(e) {
e.target.result
html = '<input type="hidden" name="data" value="' + e.target.result.replace(/^.*,/, '') + '" >';
html += '<input type="hidden" name="mimetype" value="' + e.target.result.match(/^.*(?=;)/)[0] + '" >';
html += '<input type="hidden" name="filename" value="' + e.target.fileName + '" >';
html += '<input type="hidden" name="name" value="' + name + '" >';
$("#data").empty().append(html);
}
fr.readAsDataURL(file);
});
</script>
Result in Google sheet
How to get data in a readable format?
Personally, I never use forms. Here's an examples that creates 5 text boxes. Validates that you put something into them and returns the code to the server via google.script.run for further processing (i.e. Logger.log the data). I create the html server side and loaded it on the on DOM ready event with JQuery.
Codes.gs
function buildForm(){
var s='';
for(var i=0;i<5;i++){
s+=Utilities.formatString('<br /><input class="jim" type="text" value="" id="%s" />%s',"txt" + i,"text" + Number(i+1));
}
s+='<br /><input type="button" value="Submit" onClick="getValues();" /><input type="button" value="Close" onClick="google.script.host.close();" />';
return s;
}
function saveValues(A){
for(var i=0;i<A.length;i++){
Logger.log('\nid=%s\nvalue=%s',A[i].id,A[i].value);
}
}
function showFormDialog(){
var ui=HtmlService.createHtmlOutputFromFile('form')
SpreadsheetApp.getUi().showModelessDialog(ui,'My Form');
}
form.html:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(function(){
google.script.run
.withSuccessHandler(function(html){$('#form').html(html);})
.buildForm();
});
function getValues(){
var elements=document.getElementsByClassName('jim');
var el=[];
console.log('elements.length=%s',elements.length);
for(var i=0;i<elements.length;i++){
var obj={};
obj['id']='txt' + i;
obj['value']=$('#' + 'txt' + i).val();
el.push(obj);
}
var dataValid=true;
for(var i=0;i<el.length;i++){
console.log('id=%s, value=%s',el[i].id, el[i].value);
if(!el[i].value){
dataValid=false;
$('#'+el[i].id).css('background','#ffff00');
}else{
$('#'+el[i].id).css('background','#ffffff');
}
}
if(dataValid){
google.script.run.saveValues(el);
}else{
alert('Invalid Data Found...Try again sucker....');
}
}
console.log('MyCode');
</script>
<style>
input {margin:5px 5px 0 0;}
</style>
</head>
<body>
<div id="form"></div>
</body>
</html>

I need with parsing an array from google script to HTML

I have a date picker that I'd like to use to choose an event and then show details from a spread sheet.
HTML:
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$( "#datepicker" ).datepicker({
onSelect: function(date) {
var stuff= updDate(date);
},
selectWeek: true,
inline: true,
startDate: '01/01/2000',
firstDay: 1,
});
});
</script>
<script>
function updDate(date){
google.script.run.updDate(date);
}
</script>
</head>
<body>
<p>Date: <input type="text" id="datepicker" onchange="updDate()"></p>
Hello, world!
<input type="button" value="Close"
onclick="google.script.host.close()" />
</body>
</html>
Google Script:
function updDate(date){
var searchString = date;
var data = SpreadsheetApp.getActiveSheet().getDataRange().getValues();
var s2 = SpreadsheetApp.openById("*************");
var row = new Array();
var k;
for (var i in data) {
//Logger.log("length is: "+data[i].length)
//var p = data[i].length
for (var j in data[i]) {
//Logger.log("We are at i: "+i) //Row
//Logger.log("We are at j: "+j) //Col
if (i !=0){
if(data[i][j] != ""){
if(j == 4){
//Logger.log("date from picker: " + date);
//Logger.log("date from Data: " + data[i][j]);
var ssDate = Utilities.formatDate(data[i][j], "GMT", "MM/dd/yyyy");
//Logger.log("date post Convert: " +ssDate);
if(date == ssDate){
k= i
var p = data[i].length
Logger.log("P is: " +p);
}
}
}
}
}
}
Logger.log("K is: "+k)
var q = 1
while (q <= p){
row[q] = data[k][q];
q++
}
Logger.log("Row: " +row);
return row;
}
Eventually I'd like to get the data read into a table but I've been hitting a wall when it comes to successfully getting the data read into a variable in the HTML.
Right now I get this error:
Uncaught ScriptError: The script completed but the returned value is not a supported return type.
Any help in returning the array "row"(in the google script) to the variable "stuff"(in the HTML) successfully or any pointers about how to better execute this task would be greatly appreciated.
Loren
Edit code:
function updDate(date){
var stuff = google.script.run.withSuccessHandler(myReturnFunction).updDate(date);
Console.log(stuff)
}
function myReturnFunction(){
window.myReturnFunction = function(whatGotReturned) {console.log(whatGotReturned);};
}
Sandy Good had it right in the comments above:
function updDate(date){
var junk = google.script.run.withSuccessHandler(myReturnFunction).updDate(date);
}
function myReturnFunction(whatGotReturned){
console.log(whatGotReturned);
}

WebMatrix - Using ImageResizer with image upload

i've been looking into the awesome imageresizing.net tool, and am successfully using the URL API on my site.
However, i'm keen to look into the managed API, and resize a photo AS it is uploaded. I have started off by building a very basic upload page that uses the WebImage helper:
#using ImageResizer;
#{
WebImage photo = null;
var newFileName = "";
var imagePath = "";
if(IsPost){
photo = WebImage.GetImageFromRequest();
if(photo != null){
newFileName = Guid.NewGuid().ToString() + "_" +
Path.GetFileName(photo.FileName);
imagePath = #"images\" + newFileName;
photo.Save(#"~\" + imagePath);
}
}
}
I want to use the ImageResizing tool in this upload, to resize/crop to a specific size.
Below is the code that i need to insert (i have tested this by running on an existing image, and it works fine):
ImageResizer.ImageBuilder.Current.Build(imagePath,imagePath,
new ResizeSettings("width=620&height=405&mode=crop"));
Any idea house i can merge the two, and resize BEFORE i save?
You were so close! Server.MapPath is the missing piece you're looking for.
#{
if (IsPost) {
var photo = WebImage.GetImageFromRequest();
if (photo != null) {
var filename = Guid.NewGuid().ToString() + "_" + Path.GetFileName(photo.FileName);
var localPath = Server.MapPath("~/") + #"images\" + filename;
photo.Save(localPath);
ImageResizer.ImageBuilder.Current.Build(localPath, localPath, new ImageResizer.ResizeSettings("width=620&height=405&mode=crop"));
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>My Site's Title</title>
<link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />
</head>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="mahfile">
<input type="submit">
</form>
</body>
</html>

Input type=file, restrict to .rpt only

I'm using tag <input type="file" accept="application/x-rpt, magnus-internal/rpt"/> to only allow .rpt files to be uploaded, but it's unsuccessful. User still can upload whatever they want.
What's wrong here? Please help me. Thank you so much.
Put the following script in head
<script type="text/javascript">
function ValidateForm() {
var fileBox = document.getElementById("fileBox");
var val = fileBox.value;
var splittedValue = val.split(".");
//alert(splittedValue.length);
//for (var i = 0; i < splittedValue.length; i++) {
// alert(splittedValue[i]);
//}
var NthElementIndex = splittedValue.length - 1;
var nThElement = splittedValue[NthElementIndex];
if (nThElement != "jpg"
&& nThElement != "rpt") {
alert("Please select valid rpt file");
}
}
</script>
Now Use the following information for id in input tag
<input type="file" id="fileBox" />
<input type="button" onclick="ValidateForm()" value="Validate" />

createElement Unique Identifier

I am building a little gallery in Html and I am having some trouble with it. I have a for loop that creates an img every time it iterates. The problem is that once I have all the images produced and I try to pass a unique variable to my other function which displays the clicked image, there are no unique values I can pass.
I'm probably not explaining it well, but if you run it you'll see what I mean. Any help figuring out how I can obtain a unique identifier for each of the thumbnails would be greatly appreciated.
Below is the code.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function loadPictures(){
var a = new Array();
a[0] = '1-m';
a[1] = '2-m';
a[2] = '3-m';
document.getElementById('inWin').innerHTML='<img src="images/1-m.png" width="620px" height="auto" />';
var ci = document.getElementById('pics');
var newImg, divIdName;
for(x=0; x<a.length; x++)
{
newImg = document.createElement('img');
divIdName = 'portrait'+x;
newImg.setAttribute('id',divIdName);
newImg.setAttribute('src', 'images/' + a[x] + 'thumb.png');
newImg.setAttribute('onclick','changeContent(x);'); // for FF
newImg.onclick = function() {changeContent(x);}; // for IE
ci.appendChild(newImg);
}
}
</script>
<script>
function changeContent(num){
alert(num);
var a = new Array();
x=num;
a[0] = '1-m';
a[1] = '2-m';
a[2] = '3-m';
document.getElementById('inWin').innerHTML='<img src="images/'+ a[x] +'thumb.png" width="620px" height="auto" />';
}
</script>
</head>
<body onload="loadPictures()">
<div id="inWin">
</div>
<div id="pics">
</div>
</body>
</html>
Since I am a newer member I can't upload the image, sorry.
Each of the images already has a unique identifier, the ID attribute. You can work with this in different ways to get what you want. here's an idea of what it would look like:
<script>
var a = [ '1-m',
'2-m',
'3m'
];
function loadPictures(){
document.getElementById('inWin').innerHTML='<img src="images/1-m.png" width="620px" height="auto" />';
var ci = document.getElementById('pics');
var newImg, divIdName;
for(x=0; x<a.length; x++)
{
newImg = document.createElement('img');
divIdName = 'portrait'+x;
newImg.setAttribute('id',divIdName);
newImg.setAttribute('src', 'images/' + a[x] + 'thumb.png');
if(document.addEventListener)
newImg.addEventListener('click', changeContent, false);
else if(document.attachEvent)
newImg.attachEvent('onclick', changeContent);
ci.appendChild(newImg);
}
}
function changeContent(){
x = this.id.split('portrait')[1];
document.getElementById('inWin').innerHTML='<img src="images/'+ a[x] +'.png" width="620px" height="auto" />';
}
</script>