display javascript function result in another page - javascript

good evening all,
I want to know how to display the import data from page 1 to the view in page 2 calling the function GetRoute() from input .
this is my code :
Html page 1 :
<div> Add Destination</div>
<div>
<input id="travelto" type="text" name="name" value="Oving, UK" />
<input type="button" value="Add" onclick="PushDestination()" />
Tagmere, UK.
Bosham, UK
</div>
<div id="destinations"></div><br />
Source : <input id="travelfrom" type="text" name="name" value="Chichester, UK" /> <br /> <br />
<input type="button" value="Calculate" onclick="GetRoute()" />
html page2
the result will be displayed here in a table in the second page:
<div id="dvDistance">
<table id="tblResults" border="1" cellpadding="10">
<tr>
<th> Start </th>
<th> End </th>
<th> Distance </th>
<th> Duration </th>
</tr>
</table>
</div>
my function from javascript :
function GetRoute() {
directionsDisplay.setMap(map);
source = document.getElementById("travelfrom").value;
destination = document.getElementById("travelto").value;
var waypoints = [];
for (var i = 0; i < locations.length; i++) {
var address = locations[i];
if (address !== "") {
waypoints.push({
location: address,
stopover: true
});
}
}
var request = {
origin: source,
destination: waypoints[0].location,
waypoints: waypoints, //an array of waypoints
optimizeWaypoints: true, //set to true if you want google to determine the shortest route or false to use the order specified.
travelMode: google.maps.DirectionsTravelMode.DRIVING
};
directionsService.route(request, function (response, status) {
if (status == google.maps.DirectionsStatus.OK) {
var dvDistance = document.getElementById("dvDistance");
var distance = 0;
var minute = 0.00;
response.routes[0].legs.forEach(function (item, index) {
if (index < response.routes[0].legs.length - 1) {
distance = distance + parseInt(item.distance.text);
minute = parseFloat(minute) + parseFloat(item.duration.value / 60);
tbl = document.getElementById("tblResults");
var row = tbl.insertRow(1);
var cell = row.insertCell(0);
cell.innerText = source;
var cell = row.insertCell(1);
cell.innerText = item.end_address;
var cell = row.insertCell(2);
cell.innerText = distance;
var cell = row.insertCell(3);
cell.innerText = minute.toFixed(2) + " min";
}
});
directionsDisplay.setDirections(response);
}
else {
}
})
};
I have to display the result for it to be displayed in the second page, taking the data from the first page .
thnaks,

You can use HTML5 session o local storage:
sessionStorage.getItem('label')
sessionStorage.setItem('label', 'value')
or
localStorage.getItem('label')
localStorage.setItem('label', 'value')
depending on how long you want this results to be stored.

You can use the query string or the hash. Using the hash, you can then remove the hash from the url without refreshing the page. Also, you can use history.replaceState to remove the query string from the url without refreshing.
Here's an example:
http://id0t.x10.mx/StackOverflow/demo2a.html
Use it to get the source.
EDIT:
PAGE 1
<textarea onchange="sendres(myFunc(this.value),'/StackOverflow/demo2b.html');" placeholder="type in me and press enter (or click out of me) to submit!"></textarea>
<script>
function sendres(callback,url){
window.location.href=url+"?"+encodeURIComponent(callback);
}
function myFunc(text){
return text;
}
</script>
PAGE 2
<script>
window.onload=function(){
if((window.location.search.length==0)||(window.location.search.length==1)){
//no query string
document.getElementById("msg").style.display="none";
return;
}else{
res = decodeURIComponent(window.location.search.substr(1));
var url = window.location.origin+window.location.pathname;
history.replaceState({urlPath:url},"",url);
}
alert(res);
}
</script>
<span id="msg">Now, look at the URL. See how it has no query string?<br><button onclick="document.body.parentElement.innerHTML=atob();">Source</button></span>
<button onclick="window.location='/StackOverflow/demo2a.html';">to part 1</button>

we can use a Cookies for store data in it and we can use the data stored with request cookie .

Related

Need to check for login username and password, and then bring data from previous entries

Following this question I had asked previously (Need to Query Google Sheet for specific data from Google Apps Script).
I have created a web app to track the working hours of employees at my company, the web app is simple, it first asks them to provide their username and a password, and then allows them to register their time of entry o their exit time. Now, I need to find a way to check for a match between username and password (in a data base), and if this is true, bring information about that employee's last submission to the web app, this last submission data is found on another sheet that receives the data from the web app.
Here is a minimal reproducible example, where its just asks for a name and a password, and if correct, show another display, where it brings the timestamp of that user's last submission to the web app.
var name="";
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Form');
}
function AddRecord(Name) {
// get spreadsheet details
var url = 'https://docs.google.com/spreadsheets/d/1CJoPuq3sHE5L31GwlvS4Zygm1sL3M0HGC7MgW3rCq3g/edit#gid=0';
//Paste URL of GOOGLE SHEET
var ss1= SpreadsheetApp.openByUrl(url);
var webAppSheet1 = ss1.getActiveSheet();
const Lrow = webAppSheet1.getLastRow();
const data = [Name, new Date ()];
webAppSheet1.getRange(Lrow+1,1, 1, data.length).setValues([data])
}
function checklogin(Name,Password) {
var url = 'https://docs.google.com/spreadsheets/d/1CJoPuq3sHE5L31GwlvS4Zygm1sL3M0HGC7MgW3rCq3g/edit#gid=0'; //Paste URL of GOOGLE SHEET
var ss2= SpreadsheetApp.openByUrl(url);
var webAppSheet2 = ss2.getSheetByName("DataBase");
var checkuser = webAppSheet2.getRange(2, 1, webAppSheet2.getLastRow(), 1).createTextFinder(Name).matchEntireCell(true).findNext();
var obj = {checkuser: checkuser ? 'TRUE' : 'FALSE'};
var sheet = ss2.getSheetByName("ReceivedData");
var ranges = sheet.getRange(2, 1, sheet.getLastRow(), 1).createTextFinder(Name).matchEntireCell(true).findAll();
if (ranges.length > 0) {
obj.lastTimestamp = ranges.pop().offset(0, 1, 1, 1).getDisplayValue();
return obj;
}
return obj;
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<style>
#LastR{
display: inline-block;
}
</style>
<script>
function AddRow()
{
var Name = document.getElementById("Name").value;
google.script.run.AddRecord(Name);
document.getElementById("Name").value = '';
}
function LoginUser() {
var Name = document.getElementById("Name").value;
var Password = document.getElementById("Password").value;
google.script.run.withSuccessHandler(function({checkuser, lastTimestamp}) {
if(checkuser == 'TRUE') {
document.getElementById("loginDisplay").style.display = "none";
document.getElementById("dataDisplay").style.display = "block";
document.getElementById("lastTimestamp").innerHTML = lastTimestamp;
} else if(checkuser == 'FALSE') {
document.getElementById("errorMessage").innerHTML = "Name not found";
}
}).checklogin(Name,Password);
}
</script>
</head>
<body>
<div id="loginDisplay">
<div>
<label>Name</label><br>
<input type="text" id="Name" />
</div>
<div>
<label>Password</label><br>
<input type="text" id="Password" />
</div>
<div class="btn">
<input value="Login" onclick="LoginUser()"
type="button">
<span id="errorMessage"></span>
</div>
</div>
<div style="display:none" id="dataDisplay">
<div>
<label>Last Registration</label>
<br><br>
<div class="LastR" id="lastTimestamp"></div>
<button type="button" value="Add" onclick="AddRow()">Send</button>
</div>
</div>
</body>
</html>
And here is a sheet where you can work from or copy the information.
https://docs.google.com/spreadsheets/d/1CJoPuq3sHE5L31GwlvS4Zygm1sL3M0HGC7MgW3rCq3g/edit#gid=0
I believe your goal as follows.
You want to search the inputted values of Name and Password from DataBase sheet in the Spreadsheet.
You want to show the last timestamp retrieved from ReceivedData sheet by searching the inputted values from DataBase sheet.
In this case, I would like to propose to modify var obj = {checkuser: checkuser ? 'TRUE' : 'FALSE'}; of the function checklogin for achieving your goal as follows.
From:
var obj = {checkuser: checkuser ? 'TRUE' : 'FALSE'};
To:
var obj = {checkuser: checkuser && checkuser.offset(0, 1).getValue() == Password ? 'TRUE' : 'FALSE'};
In this modification, the inputted Name value is searched from the 1st column, and then, Password is checked from the 2nd column with the same row of the searched 1st column. And, when the both values are same, TRUE is returned.
Reference:
offset(rowOffset, columnOffset)

Output filter results into a text box

I'm trying to create a web apps script with a field that accepts user input and returns the result(s). I need it to list all the results associated with the input query.
Things I've tried doing:
I've assigned an actual order number to orderInput and I was able to get the results I wanted it to return using Logger.log(orderMatch) so I know it works.
I wasn't sure if I was running into a formatting issue so I tried converting orderInput to a string with orderInput.toString() and that didn't work.
At first I was trying to display it in a disabled input field and that didn't work so I tried using a textarea but that didn't work either.
I've also tried moving the document.getElementById("orderResults").value = (orderMatch);
M.updateTextFields(); in various places between return item[0] === orderInput
});
I was using document.getElementById("orderNumber").addEventListener("change",orderLookup); to trigger the script from running but I also tried creating a button with onclick="orderLookup()" but that didn't work.
This is my script:
function orderLookup() {
var orderSheet = "Google Spreadsheet URL"
var ss = SpreadsheetApp.openByUrl(orderSheet);
var ws = ss.getSheetByName("Orders");
var originalSheet = ws.getRange(2, 1, ws.getLastRow() - 1, 3).getValues();
var orderInput = document.getElementById("orderNumber").value;
var orderMatch = originalSheet.filter(function(item) {
return item[0] === orderInput
});
document.getElementById("orderResults").value = (orderMatch);
M.updateTextFields();
}
As for my HTML:
<div class="input-field col s2">
<input value="" id="orderNumber" type="text" class="validate">
<label class="active" for="orderNumber">Enter Order Number</label>
</div>
<center style="float:left;margin-left:0px;margin-top:0px;">
<h6><b>Results</b></h6>
<textarea id="orderResults" rows="10" cols="45" disabled="disabled" style="width:100%; height:auto"></textarea>
</center>
Well it looks to me like your mixing server side functions with client side functions and I'm guessing that since you provide html code and script that you trying to run is client side.
function orderLookup() {
var orderSheet = "Google Spreadsheet URL"
var ss = SpreadsheetApp.openByUrl(orderSheet);//Server side function
var ws = ss.getSheetByName("Orders");//Server side function
var originalSheet = ws.getRange(2, 1, ws.getLastRow() - 1, 3).getValues();//Server Side function
var orderInput = document.getElementById("orderNumber").value;//Client Side Function
var orderMatch = originalSheet.filter(function(item) {return item[0]===orderInput});//could be either
document.getElementById("orderResults").value = (orderMatch);
M.updateTextFields();//dont know
}
Assuming that:
You want to look for the data in the sheet when Enter Order Number is clicked.
You want to look for rows where first column matches the input you provided.
You want all the data in the row to show up in the <textarea> element.
A possible solution would be the following:
Create an onclick event in the label, which will run a function on the client side:
<label class="active" for="orderNumber" onclick="search()">Enter Order Number</label>
Next, the following function is run by the onclick event. This function calls a server-side function (orderLookup) which will look for matching data in the sheet and return the results.
function search() {
var input = document.getElementById("orderNumber").value;
google.script.run.withSuccessHandler(showResults).orderLookup(input);
}
Here is function orderLookup:
function orderLookup(input) {
var orderSheet = "Google Spreadsheet URL"
var ss = SpreadsheetApp.openByUrl(orderSheet);
var ws = ss.getSheetByName("Orders");
var values = ws.getRange(2, 1, ws.getLastRow() - 1, 3).getValues();
var orderMatch = values.filter(function(item) {
return item[0] === input
});
return orderMatch;
}
If orderLookup returns a value, another client-side function will run, which will get the matching data as a parameter, and will write it to the <textarea>:
function showResults(orderMatch) {
var matches = "";
for(var i = 0; i < orderMatch.length; i++) {
matches = matches.concat(orderMatch[i], "\n");
}
document.getElementById("orderResults").value = matches;
}
So, full code would be the following:
index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<div class="input-field col s2">
<input value="" id="orderNumber" type="text" class="validate">
<label class="active" for="orderNumber" onclick="search()">Enter Order Number</label>
</div>
<center style="float:left;margin-left:0px;margin-top:0px;">
<h6><b>Results</b></h6>
<textarea id="orderResults" rows="10" cols="45" disabled="disabled" style="width:100%; height:auto"></textarea>
</center>
</body>
<script>
function search() {
var input = document.getElementById("orderNumber").value;
google.script.run.withSuccessHandler(showResults).orderLookup(input);
}
function showResults(orderMatch) {
var matches = "";
for(var i = 0; i < orderMatch.length; i++) {
matches = matches.concat(orderMatch[i], "\n");
}
document.getElementById("orderResults").value = matches;
}
</script>
</html>
Code.gs
function doGet() {
return HtmlService.createHtmlOutputFromFile('index');
}
function orderLookup(input) {
var orderSheet = "Google Spreadsheet URL"
var ss = SpreadsheetApp.openByUrl(orderSheet);
var ws = ss.getSheetByName("Orders");
var values = ws.getRange(2, 1, ws.getLastRow() - 1, 3).getValues();
var orderMatch = values.filter(function(item) {
return item[0] === input;
});
return orderMatch;
}
I hope this is what you wanted to accomplish.

send from first html to java script in another html

I have two html, first sends value to another. I want in second html receive data in javascript. On first html page user would be able to insert localhost:8888 address, address should be send to java script in another html...for now i have default address in java script .. please help.
first html
<form action="second.html" method="GET" >
<input type="text" name="" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
second html
<script>
$(document).ready(function () {
var ws = new WebSocket("ws://localhost:8888/ws");
ws.onopen = function(evt) {
var conn_status = document.getElementById('conn_text');
conn_status.innerHTML = "Status: Connected!"
};
...
got more code
<script>
...
You can get submitted data from URL, because your from has submit method GET:
first html:
<form action="second.html" method="GET" >
<!-- In this way we can get submitted data from get param "host" -->
<input type="text" name="host" />
<input type="submit" value="Submit" />
</form>
second html:
<script>
$(document).ready(function () {
// function to get params from url
function getQueryParams(query) {
query = query || window.location.search;
if (query.length === 0) {
return {};
}
var params = {};
var paramsArr = query.split('&');
for (var i = 0; i < paramsArr.length; i++) {
var p = paramsArr[i].split("=");
params[p[0]] = p[1] || '';
}
return params;
}
// try to get param "host" from url (which submitted from first html)
var queryParams = getQueryParams();
var host = queryParams.host || 'localhost:8888';
var ws = new WebSocket('ws://' + host + '/ws');
ws.onopen = function (evt) {
var conn_status = document.getElementById('conn_text');
conn_status.innerHTML = "Status: Connected!"
};
// more code
}
</script>

how to find lat ,long of a given area using pin code

hi i am using Bing map in my website and want lat long to pinpoint that location on Bing map. my question is in my website how can i get lat long of an area using pincode. Is there any api that i can use to query lat long with by giving area pin code. i want to do it in backend. using some ajax call to that particular web api and get back lat lang and saved it into database so that i can use that lat long to plot location on my bing map.
i am using bing map 7 where i need to put lat long value into a json object and pass it into Bing map.
function GetMap()
{
var mapOptions = {
credentials: "Your Bing Maps Key",
center: new Microsoft.Maps.Location(47.592, -122.332), // i want these value in my database
mapTypeId: Microsoft.Maps.MapTypeId.birdseye,
zoom: 17,
showScalebar: false
}
var map = new Microsoft.Maps.Map(document.getElementById("mapDiv"), mapOptions);
}
i can hard code it but in my application i have given client an option which is use to add new location so in back end i want it like when client add any new location it automatically save its lat long also.
thanks
Using pincodes for obtaining the lat, long values may not be the best solution, since pin codes though popular for more than a century are still not a standard round the world. for example in US pincodes (zip codes) are normally have 5 digits (i.e. 06160) and in my part of the world their are normally 6 digits or more..
Though you can use combination of street address, state, country and pin code to find out the nearly correct geo coordinates for almost every part of the world. See following script which calls google api for finding the Lat, Long value... Here by I donate this code to the community under GPL:-
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"> </script>
<script src="http://maps.google.com/maps?file=api&v=3&key=ABQIAAAA7j_Q-rshuWkc8HyFI4V2HxQYPm-xtd00hTQOC0OXpAMO40FHAxT29dNBGfxqMPq5zwdeiDSHEPL89A" type="text/javascript"> </script>
<script type="text/javascript">
var geocoder, location1;
function initialize() {
geocoder = new GClientGeocoder();
}
function prepareQuery(){
var query='';
var a1 = document.getElementById('address1').value;
var a2 = document.getElementById('address2').value;
var a3 = document.getElementById('address3').value;
var cty = document.getElementById('city').value;
var stat = document.getElementById('state').value;
var cntry =document.getElementById('country').value;
var pin = document.getElementById('pincode').value;
if(a1 != null && a1!=''){
query = query + a1 + ",";
}
if(a2 != null && a2!=''){
query =query + a2 + ",";
}
if(a3 != null && a3!=''){
query = query + a3 + ",";
}
if(cty != null && cty!=''){
query = query + cty + ",";
}
if(stat != null && stat!=''){
query = query + stat + ",";
}
if(cntry != null && cntry!=''){
query = query + cntry + ",";
}
if(pin != null && pin!=''){
query = query + pin + ",";
}
// alert("Prepare Query Returns " +query);
return query;
}
function submitFunc(){
var location = prepareQuery();
geocoder.getLocations(location, function (response) {
if (!response || response.Status.code != 200)
{
alert("Sorry, we were unable to geocode the address");
}
else
{
location1 = {latitude: response.Placemark[0].Point.coordinates[1], longitude: response.Placemark[0].Point.coordinates[0], Address : response.Placemark[0].address};
var items = [];
$.each(location1, function(key, value){
items.push('<li id="' + key + '">' + key +" : "+ value + '</li>');
});
// alert(items)
$("body").append("Results is :-");
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
}
});
}
</script>
and the html looks like....
Line 1 : <input type="text" id="address1" value="" placeholder="Enter first line of address."/> <br></br>
Line 2 :<input type="text" id="address2" value="" placeholder="Enter second line of address."/> <br></br>
Line 3 :<input type="text" id="address3" value="" placeholder="Enter third line of address."/> <br></br>
City : <input type="text" id="city" value="" placeholder="Enter city name."/> <br></br>
State : <input type="text" id="state" value="" placeholder="Enter state name."/> <br></br>
Country : <input type="text" id="country" value="" placeholder="Enter country name."/> <br></br>
Pin Code : <input type="text" id="pincode" value="" placeholder="Enter pincode value."/> <br></br>
<input type="button" name="submitBtn" value="submit" onclick='submitFunc();'/> <br></br>
<h3> <strong> Your Results Will be displayed Here . . . .</strong> </h3>
Geonames is a good service for all kind of location stuff, take a look at the list of the services they provide:
http://www.geonames.org/export/ws-overview.html
Could you use the one to look up postal codes? api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo

How to write data from Form in HTML to XML with Javascript

This is an assignment from my class. What I need to do is create a registration page. When the user presses the submit button, I have take all the information on the form and write it to an existing XML file using Javascript. This is done on the client side, only through HTML, Javascript, and XML. By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves. Also, I'm not too familiar with Javascript, especially with the built in functions, if possible please explain what each line or method of code is doing.
Let me begin, here's how my existing XML looks like:
<?xml version ="1.0" encoding="utf-8" ?>
<!--GGFGFGFVBFVVVHVBV-->
<PersonInfo>
<Person Usrname="Bob111" Pswd="Smith111" personid="111" FirstName="Bob" LastName="Smith" DOB="01/01/1960" Gender="M" Title="Hello1">
</Person>
<!-- several more lines of <person> here -->
</PersonInfo>
When saving the form data, it has to follow all the layout within , basically I would need Usrname, Pswd, personid, and so on.
Basically, from what I understand, I have to create the XML line "Person" from my registration page once I press submit. Then push it to the array that already have my XML information, then write over my XML document with the information on the array. My problem is, I have exactly no idea how to do that.
For those who wants to know how my registration page looks like, here it is:
<html>
<head>
<title>Registration</title>
<link rel="stylesheet" type="text/css" href="CSS_LABs.css" />
</head>
<body>
<div class="form">
<form id="Registration" action="" method="get">
Username:<input type="text" name="usrname" maxlength="10"/> <br/>
Password:<input type="password" name="pswd" maxlength="20"/> <br/>
<hr>
PersonID:<input type="text" name="PID" /> <br>
<hr>
First Name:<input type="text" name="fname"/> <br>
Last Name:<input type="text" name="lname"/>
<hr>
DOB:<input type="text" name="dob" /> <br>
<hr>
Gender:<input type="text" name="sex" /> <br>
<hr>
Title:<input type="text" name="title" /> <br>
<hr>
Secret Question:<br>
<select name="secret?">
</select> <br>
Answer:<input type="text" name="answer" /> <br> <br>
<input type="submit" value="submit" />
</form>
</div>
</body>
</html>
By the way, I know certain information on my HTML document may not be worded properly, so do hope you guys don't mind. Also, I would also have to fix up my XML later by putting the answer to the secret question within later.
Alright, thanks a lot in advance guys.
UPDATE!!!
Here we go, I finally figured out how to create an XML document with Javascript, here's the code:
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME = 'G:\\CST2309 - Web Programming 1\\Copy of Take Home Exam - Copy\\PersonXML2.xml';
function SaveXML(UserData)
{
var file = fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8"?>\n');
file.WriteLine('<PersonInfo>\n');
for (countr = 0; countr < UserData.length; countr++) {
file.Write(' <Person ');
file.Write('Usrname="' + UserData[countr][0] + '" ');
file.Write('Pswd="' + UserData[countr][1] + '" ');
file.Write('PersonID="' + UserData[countr][2] + '" ');
file.Write('FirstName="' + UserData[countr][3] + '" ');
file.Write('LastName="' + UserData[countr][4] + '" ');
file.Write('Gender="' + UserData[countr][5] + '" ');
file.Write('DOB="' + UserData[countr][6] + '" ');
file.Write('Title="' + UserData[countr][7] + '"');
file.WriteLine('></Person>\n');
} // end for countr
file.WriteLine('</PersonInfo>\n');
file.Close();
} // end SaveXML function --------------------
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
return xmlDoc.documentElement;
} //end function LoadXML()
function initialize_array()
{
var person = new Array();
var noFile = true;
var xmlObj;
if (fso.FileExists(FILENAME))
{
xmlObj = LoadXML(FILENAME);
noFile = false;
} // if
else
{
xmlObj = LoadXML("PersonXML.xml");
//alert("local" + xmlObj);
} // end if
var usrCount = 0;
while (usrCount < xmlObj.childNodes.length)
{
var tmpUsrs = new Array(xmlObj.childNodes(usrCount).getAttribute("Usrname"),
xmlObj.childNodes(usrCount).getAttribute("Pswd"),
xmlObj.childNodes(usrCount).getAttribute("PersonID"),
xmlObj.childNodes(usrCount).getAttribute("FirstName"),
xmlObj.childNodes(usrCount).getAttribute("LastName"),
xmlObj.childNodes(usrCount).getAttribute("Gender"),
xmlObj.childNodes(usrCount).getAttribute("DOB"),
xmlObj.childNodes(usrCount).getAttribute("Title"));
person.push(tmpUsrs);
usrCount++;
} //end while
if (noFile == false)
fso.DeleteFile(FILENAME);
SaveXML(person);
} // end function initialize_array()
What this code here is doing is that, it takes my original XML file and loads it up into an array so it can create a new XML file. Basically I got the creating the XML file part down, but still need help with the rest of my stuff.
My goal is trying to take my form data and push it into my existing array, not overwrite it, add to it, so I can update my existing XML file with the new registration information. This is where I have absolutely no idea how to do. Some pointers would be nice.
By the way, my Professor purposely did not teach us how to do this because he wants us to research on it by ourselves.
Which should give you a hint about searching a bit more deeply. Anyhow, I'm not going to comment on every line, but I will offer some hints.
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
That is a Microsoft proprietary way of creating an XML document and it is normally wrapped in try..catch as different ActiveXObjects are provided in different versions of IE. You also need to look for document.implementation.createDocument.
//DEFINE LOAD METHOD
function LoadXML(xmlFile)
{
xmlDoc.load(xmlFile);
You might want to check out the async parameter.
xmlObj = xmlDoc.documentElement;
}
//declare & initialize array
var arrPerson = new Array();
It is considered better practice to use an array literal: ... = [];
//initialize array w/ xml
function initialize_array()
{
LoadXML("PersonXML.xml");
var x = 0;
while (x < xmlObj.childNodes.length)
Getting the length of xmlObj.childNodes on every loop is inefficient, consider storing the length and comparing with that value.
{
var tmpArr = new Array(xmlObj.childNodes(x).getAttribute("Usrname"),
xmlObj.childNodes(x).getAttribute("Pswd"),
xmlObj.childNodes(x).getAttribute("FirstName"),
xmlObj.childNodes(x).getAttribute("LastName"),
xmlObj.childNodes(x).getAttribute("DOB"),
xmlObj.childNodes(x).getAttribute("Gender"),
xmlObj.childNodes(x).getAttribute("Title"));
It is very inefficient to access xmlObj.childNodes(x) repeatedly. Store a reference and reuse it.
arrPerson.push(tmpArr);
You could assign the values directly to arrPerson and get rid of tmpArr.
x++;
Using a plain for loop will increment x for you.
}
}
//Validation
function LogInVal(objtxt)
{
if(objtxt.value.length == 0)
{
objtxt.style.background = "red";
return 1;
}
else
{
objtxt.style.background = "white";
return 0;
}
}
Not all browsers will let you style the background color of input elements.
//main validation
function MainVal(objForm)
{
var errmsg = "empty field";
var errmsg2 = "Incorrect Username and Password";
You might want a better way of naming the error messages and relating them to other information for that message. An object might do the job.
var msg = "You have logged in successfully";
var errCount = 0;
var usrn = document.getElementById("usrname1").value;
var pswd = document.getElementById("pswd1").value;
errCount += LogInVal(objForm.usrname);
errCount/*1*/ += LogInVal(objForm.pswd);
initialize_array();
if (errCount != 0)
{
alert(errmsg);
return false;
}
else if(authentication(usrn, pswd) == true)
The function authentication() returns true or false, so you don't need to compare it to anything, you can just test the returned value (i.e. there is no need for == true above).
{
alert(msg);
return true;
setCookie('invalidUsr',' ttttt');
}
else
{
alert(errmsg2);
return false;
}
}
Instead of showing alert messages one at a time in an alert, consider putting them in the document adjacent to the elements they relate to. That way the user can see the messaeg while fixing the error.
Isn't it cheating to ask us? Your implementation will probably only work in IE, I'd recommend using jQuery as it is impressively powerful at parsing XML.
I'm not sure why he wants you to write out XML as it's not very intuitive coming from JavaScript. You can do something like this via jQuery
//I capture form submitevent
$('form').submit(function( ev ){
ev.preventDefault(); //I keep form from submitting
$( xmlDocument ).find('Person').attr({
username: $("input[name=usrname]),
password: $("input[name=pswd]),
//and so on
});
});
It's up to you on how you 'report' this xml file
Here i am sharing my experience in writing html form data to xml.
Create one html file in one location (D:\\HtmlToXml.html).
And open it with Internet Explorer.
Then after provide information and click on submit button, then one file is created in the same directory with name example.xml.
If once an xml is created, then next time onwards on submit button click data will append to same xml file.
<!DOCTYPE html>
<html>
<head>
<title>Display Emp Details</title>
<script type="text/javascript" language="javascript">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var FILENAME='D:\\example.xml';
function SaveXMLData()
{
validations();
}
function createfile()
{
var file;
var e1=document.getElementById('empName').value;
var p1=document.getElementById('empNumber').value;
var em1=document.getElementById('empEmail').value;
var d1=document.getElementById('empDate').value;
var tablemain = document.getElementById('tblmain');
if(fso.fileExists(FILENAME))
{
xmlDoc.load(FILENAME);
var lng;
lng=xmlDoc.getElementsByTagName("Details");
var xmlread= fso.OpenTextFile(FILENAME,1,true,0);
var x=xmlread.readAll();
var replace=x.replace('</Emp>','');
var sno=lng.length + 1;
file=fso.OpenTextFile(FILENAME,2,true);
file.writeLine(replace);
file.WriteLine('<Details category="'+sno+'">');
file.WriteLine('<SNo>'+sno+'</SNo>');
file.WriteLine('<Name>'+e1+'</Name>');
file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
file.WriteLine('<Emailid>'+em1+'</Emailid>');
file.WriteLine('<Date>'+d1+'</Date>');
file.WriteLine('</Details>');
file.WriteLine('</Emp>');
alert('another file updated');
}
else
{
file= fso.CreateTextFile(FILENAME, true);
file.WriteLine('<?xml version="1.0" encoding="utf-8" ?>');
file.WriteLine('<?xml-stylesheet type="text/xsl" href="cdcatalog.xsl"?>');
file.WriteLine('<Emp>');
file.WriteLine('<Details category="1">');
file.WriteLine('<SNo>'+1+'</SNo>');
file.WriteLine('<Name>'+e1+'</Name>');
file.WriteLine('<PhoneNumber>'+p1+'</PhoneNumber>');
file.WriteLine('<Emailid>'+em1+'</Emailid>');
file.WriteLine('<Date>'+d1+'</Date>');
file.WriteLine('</Details>');
file.WriteLine('</Emp>');
alert('file updated');
}
<!-- displayData();-->
document.getElementById('empName').value='';
document.getElementById('empNumber').value='';
document.getElementById('empEmail').value='';
document.getElementById('empDate').value='';
addRow('tablemain');
file.close();
}
function validations()
{
var emp1=document.getElementById('empName').value;
var letters = /^[\s A-Za-z]+$/;
if(emp1!="")
{
if(emp1.match(letters))
{
allnumeric();
}
else
{
alert('Please input alphabet characters only');
return false;
}
}
else
{
alert('Please Enter Name.');
}
}
<!--For checking Email-->
function checkemail()
{
var email = document.getElementById('empEmail');
var filter = /^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if(email.value!="")
{
if (!filter.test(email.value))
{
alert('Please provide a valid email address');
return false;
}
else
{
DateValidation();
}
}
else
{
alert('Please Enter Email.');
}
}
<!--For checking Date Format-->
function DateValidation()
{
var date=/^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{2,4}$/;
var empDate=document.getElementById("empDate");
if(empDate.value!="")
{
if(empDate.value.match(date))
{
createfile();
}
else
{
alert("Please provide valid date : DD-MM-YY(YYYY)");
return(false);
}
}
else
{
alert('Please Enter Date.');
}
}
<!--For checking phone number-->
function allnumeric()
{
var numbers=/^\d{10}$/;
var empNumber=document.getElementById("empNumber");
if(empNumber.value!="")
{
if(empNumber.value.length=="10")
{
if(empNumber.value.match(numbers))
{
checkemail();
}
else
{
alert("Phone number should be numeric");
return(false);
}
}
else
{
alert('Phone Number should be like: 9876543210');
}
}
else
{
alert('Please Enter Phone Number.');
}
}
function addRow(id)
{
if(fso.fileExists(FILENAME))
{
xmlDoc.load(FILENAME);
var x;
x=xmlDoc.getElementsByTagName("Details");
var table = document.getElementById('tbl');
var nxtbtn= document.getElementById("btnnext");
var prvbtn=document.getElementById("btnprev");
nxtbtn.disabled=true;
prvbtn.disabled=true;
if(x.length >5)
{
nxtbtn.disabled=false;
}
var j=0;k=5;
if(k>x.length)
{k=x.length;}
var store=document.getElementById("txtstore");
var maxval=document.getElementById("txtmax");
if(id=="btnprev")
{
if((store.value % k)==0)
{
store.value = store.value - k ;
if(store.value>0)
{
j = parseInt(store.value);
k += parseInt(store.value);
}
}
else
{
store.value =store.value - (store.value % k) ;
if(store.value >0)
{
j = store.value - k;
k = store.value;
}
}
if(j > 0)
{
prvbtn.disabled=false;
}
}
if(id=="btnnext")
{
if(store.value==0)
{
store.value=table.rows.length;
}
else if(store.value <0)
{
store.value=maxval.value;
}
prvbtn.disabled=false;
if(store.value >=k)
{
j +=parseInt(store.value);
k +=parseInt(store.value);
if(k >= x.length)
{
k=x.length;
nxtbtn.disabled = true;
prvbtn.disabled = false;
}
}
}
table.innerHTML = "";
var rowCount = 0;
for (i=j;i<k;i++)
{
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.id = "id2" ;
cell1.appendChild(element1);
// Create label
var label = document.createElement("label");
label.htmlFor = "id2" ;
cell1.appendChild(label);
var cell2 = row.insertCell(1);
cell2.innerHTML = x[i].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;
var name = row.insertCell(2);
var elname =document.createElement("input");
elname.type = "text";
elname.readOnly=true;
elname.value=x[i].getElementsByTagName("Name")[0].childNodes[0].nodeValue;
name.appendChild(elname);
var phnno = row.insertCell(3);
var elphn =document.createElement("input");
elphn.type = "text";
elphn.readOnly=true;
elphn.value=x[i].getElementsByTagName("PhoneNumber")[0].childNodes[0].nodeValue;
phnno.appendChild(elphn);
var email = row.insertCell(4);
var elemail =document.createElement("input");
elemail.type = "text";
elemail.readOnly=true;
elemail.value=x[i].getElementsByTagName("Emailid")[0].childNodes[0].nodeValue;
email.appendChild(elemail);
var date = row.insertCell(5);
var eldate =document.createElement("input");
eldate.type = "text";
eldate.readOnly=true;
eldate.value=x[i].getElementsByTagName("Date")[0].childNodes[0].nodeValue;
date.appendChild(eldate);
rowCount +=1;
}
maxval.value=x[table.rows.length - 1].getElementsByTagName("SNo")[0].childNodes[0].nodeValue;
if(id=="btnprev")
{
store.value =store.value - 5;
}
else
{
store.value =parseInt(k);
}
}
}
</script>
</head>
<body onload="addRow('tbl')">
<form id="empForm" action="" method="get">
<p><b>Emp Registration:</b></p>
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="empName" maxlength="25"/></td>
</tr>
<tr>
<td>Phone Number:</td>
<td><input type="text" id="empNumber" maxlength="10"/></td>
</tr>
<tr>
<td>EmailId:</td>
<td><input type="text" id="empEmail"/></td>
</tr>
<tr>
<td>Date:</td>
<td><input type="text" id="empDate" maxlength="10"/></td>
</tr>
<tr>
<td align="center">
<input type="button" value="Submit" onclick="SaveXMLData()"/></td>
<td>
<input type="button" value="Show Data" id="show" onclick="displayData(this.id)" style="display:none;"/></td>
</tr>
</table>
<!-- <table><tr><td><input type="button" onclick="displayData(this.id)" value="Prev" id="prev" disabled="disabled"></td>
<td><input type="button" onclick="displayData(this.id)" value="Next" id="next" disabled="disabled"></td></tr></table> -->
<div id='displaydatadiv'>
</div>
<!-- <INPUT type="button" value="Add Row" onclick="addRow('tbl')" /> -->
<div style="height: 135px; width:650px; background-color: Lavender;" >
<TABLE id="tbl" width="350px">
</TABLE>
</div>
<table id="tblmain" border="1" style="display:true" ></table>
<input type="button" id="btnprev" value="Prev" onclick="addRow(this.id)" disabled="disabled">
<input type="button" id="btnnext" value="Next" onclick="addRow(this.id)" disabled="disabled">
<input type="hidden" id="txtstore" style="display:none;">
<input type="hidden" id="txtmax" style="display:none;">
</body>
</html>

Categories