I am trying to create a contact form that emails all the data.i have various problems with php and such,so i decided for an alternative-google MailApp.
the problem started when i wanted to attach a file with that email.
when i run the form sends the data to the script,i get an error,which suggests that file cannot be sent as parmeter in an event.
here is the mailApp script:
var TO_ADDRESS = "someone#gmail.com"; // change this ...
function doGet(e){
doPost(e);
}
function formatMailBody(obj) { // function to spit out all the keys/values from the form in HTML
var result = "";
for (var key in obj) { // loop over the object passed to the function
result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + obj[key] + "</div>";
// for every key, concatenate an `<h4 />`/`<div />` pairing of the key name and its value,
// and append it to the `result` string created at the start.
}
return result; // once the looping is done, `result` will be one long string to put in the email body
}
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
record_data(e);
var mailData = e.parameters; // just create a slightly nicer variable name for the data
var blob = e.parameter.fileToUpload;
MailApp.sendEmail({
to: TO_ADDRESS,
subject: "Contact form submitted",
htmlBody: formatMailBody(mailData),
attachments: [blob]
});
return ContentService // return json success results
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
}
}
/**
* record_data inserts the data received from the html form submission
* e is the data received from the POST
*/
function record_data(e) {
Logger.log(JSON.stringify(e)); // log the POST data in case we need to debug it
try {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName('responses'); // select the responses sheet
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1; // get next row
var row = [ new Date() ]; // first element in the row should always be a timestamp
// loop through the header columns
for (var i = 1; i < headers.length; i++) { // start at 1 to avoid Timestamp column
if(headers[i].length > 0) {
row.push(e.parameter[headers[i]]); // add data to row
}
}
// more efficient to set values as [][] array than individually
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
}
catch(error) {
Logger.log(e);
}
finally {
return;
}
}
also here is the form that sends the info:
<form name ="frm"
method ="post"
action="https://script.google.com/macros/s/AKfycbwnz1pa4p8tzf5wPqdlvgy7YVU1qPWV_ZQvX84ecSetjMX8pL8/exec"
enctype="multipart/form-data"
>
<table>
<tr>
<td><p align="right" style="width:90%;"><input name="email" type="email" required placeholder="your.name#email.com" class="form-control"></p></td>
<td>email</td>
</tr>
<tr>
<td><p align="right" style="width:90%;"><input name="subject" type="text" placeholder="subject" class="form-control"></p></td>
<td>subject</td>
</tr>
<tr>
<td><p align="right" style="width:90%;"><textarea rows="15" cols="40" name="comment" placeholder="write the message" class="form-control" ></textarea></p></td>
<td>comment</td>
</tr>
<tr>
<td><input type="file" name="fileToUpload" id="fileToUpload"/></td>
<td>file</td>
</tr>
<tr>
<td><input type ="submit" name="submit" class="btn btn-primary" value ="send"/></td>
<td><input type ="reset" class="btn btn-primary" value ="reset" /></td>
</tr>
</table>
</form>
i would really appreciate any help,as this is a totally a new thing for me.
Related
I have a program that makes a table using json data. This technique uses template liretals, so i can add rows myself however i want. My problem is that I need to get data from an input, which has a template literal as an id, but the getElementById doesn't allow me to.
I have already tried escaping my brackets, but that doesn't work. I have looked into using a simple index, but i don't know how I could set it up in my function.
Here is the javascript code:
//load JSON file
var articles = ""
var txt = ""
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status == 200 && xmlhttp.readyState == 4){
articles = xmlhttp.responseText;
txt = JSON.parse(articles);
processArticles(txt);
processForm(txt);
}
};
xmlhttp.open("GET","../articles.json",true);
xmlhttp.send();
function processArticles(txt) {
var tableStart = `
<h2>Liste des articles</h2>
<form id="formtable">
<table>
<tr>
<th>ID</th>
<th>Article</th>
<th>Prix</th>
<th>Prix-Retour</th>
<th>Quantitée maximale</th>
<th>Projet</th>
<th>Quantitée</th>
</tr>`;
var tableEnd = `
</table>
<input type="submit">
</form>`;
function articlesTemplate(txt, index) {
return `
<tr>
<td>${txt.ID}</td>
<td>${txt.Article }</td>
<td>${txt.Prix}</td>
<td>${txt.PrixRetour}</td>
<td>${txt.QuantiteeMaximale}</td>
<td>${txt.Projet}</td>
<td><input type="number" name="quantity${txt.ID}" id="quantity${txt.ID}" min="1" max="5"></td>
</tr>
`;
}
let mctxt=txt.filter(value=>
value.Projet=="mc");
document.getElementById("tablemc").innerHTML = `
${tableStart}
${mctxt.map(articlesTemplate).join("")}
${tableEnd}
`;
;
}
The problem is in the .getElementById of my quantity in this last function.
function processForm(txt) {
var form = document.getElementById('formtable');
var quantity = document.getElementById(`"quantity$\\{txt.ID\\}"`);
form.onsubmit = function(e) {
e.preventDefault();
console.log("HI");
console.log(quantity.value);
};
}
I want to be able to collect the quantity of each object selected and also the price of that same object, so that i can make a total price at the end of the table.
I think you accidentally did bad quoting like #DontVoteMeDown already mentioned.
Lets assume
txt.ID = 2
then the template string
`<input ... id="quantity${txt.ID}" />`
will result in
<input ... id="quantity2" />
as well as the selector's template string
document.getElementById(`quantity${txt.ID}`);
will result in
document.getElementById("quantity2");
So it should work in general.
If you want to sum all input values of the resulting table, you have to select all inputs and iterate over the values.
var total = 0;
document.querySelectorAll('#formtable input').forEach(function(input) {
total += parseInt(input.value);
})
I want to send an email to a location target#example.com using google script . I am following this - https://github.com/dwyl/html-form-send-email-via-google-script-without-server to setup the whole functionality in my website.
There is an html form in my website and I want to send email whenever someone clicks on the submit button on my site
here is the html of the form -
<form id="gform" method="POST" action="https://script.google.com/macros/s/AKfycbyacpl2YxzZIVDPuizRqrzedC-7mAtMywSvoVbfLbebA6MdkUKs/exec">
<div class="form-group">
<label for="exampleInputEmail1">Your Name (required)</label>
<input type="text" class="form-control" name="name" id="exampleInputEmail1" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Your Email (required)</label>
<input type="Email" class="form-control" name="email" id="exampleInputPassword1" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Your Phone Number (required)</label>
<input type="text" class="form-control" name="phone-num" id="exampleInputPassword1" required>
</div>
<div class="form-group">
<label for="exampleInputPassword1">Subject</label>
<input type="text" class="form-control" name="subject" id="exampleInputPassword1">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Message</label>
<textarea class="message" name="message"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
Here is the script.g file which is working fine -
var TO_ADDRESS = "target#example.com"; // where to send form data
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
MailApp.sendEmail(TO_ADDRESS, "Contact Form Submitted",
JSON.stringify(e.parameters));
// return json success results
return ContentService
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
}
}
I wanted to style the json object which is getting passed so when I use the following script -
// if you want to store your email server-side (hidden), uncomment the next line
var TO_ADDRESS = "target#example.com";
// spit out all the keys/values from the form in HTML for email
function formatMailBody(obj, order) {
var result = "";
// loop over all keys in the ordered form data
for (var idx in order) {
var key = order[idx];
result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + obj[key] + "</div>";
// for every key, concatenate an `<h4 />`/`<div />` pairing of the key name and its value,
// and append it to the `result` string created at the start.
}
return result; // once the looping is done, `result` will be one long string to put in the email body
}
function doPost(e) {
try {
Logger.log(e); // the Google Script version of console.log see: Class Logger
record_data(e);
// shorter name for form data
var mailData = e.parameters;
// names and order of form elements
var dataOrder = JSON.parse(e.parameters.formDataNameOrder);
// determine recepient of the email
// if you have your email uncommented above, it uses that `TO_ADDRESS`
// otherwise, it defaults to the email provided by the form's data attribute
var sendEmailTo = (typeof TO_ADDRESS !== "undefined") ? TO_ADDRESS : mailData.formGoogleSendEmail;
MailApp.sendEmail({
to: String(sendEmailTo),
subject: "Contact form submitted",
// replyTo: String(mailData.email), // This is optional and reliant on your form actually collecting a field named `email`
htmlBody: formatMailBody(mailData, dataOrder)
});
return ContentService // return json success results
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) { // if error return this
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
}
}
I get this error -
{"result":"error","error":{"parameter":{"subject":"subj",
"name":"shan","message":"msg","email":"sh#sh","phone-num":"46546"},
"contextPath":"","contentLength":64,"queryString":"","parameters":
{"subject":["subj"],"name":["shan"],"message":["msg"],"email":["sh#sh"],
"phone-num":["46546"]},"postData":{"type":"application/x-www-form-urlencoded",
"length":64,"contents":"name=shan&email=sh%40sh&phone-num=46546&subject=subj&message=msg",
"name":"postData"}}}
It happens only with the second script. Where am I going wrong ?
I'm trying to insert a form into a MySql database and while the database does, in fact, have the values stored from the for. It doesn't refresh the table being displayed on the page, only when I restart the server and visit the page again will I see the entries.
Additionally, I get a res.send is not a function type error on the line that is req.send('null').
The client side ASync ajax listener for the insert
document.getElementById('addExerciseButton').addEventListener('click',function(event){ //Add listener to addExerciseButton
var addExercise = document.getElementById("addExercise");
var request = new XMLHttpRequest();
//sets the query URL for the DB interactions
var holder ="exercise="+addExercise.elements.exercise.value+"&reps="+addExercise.elements.reps.value+"&weight="+addExercise.elements.weight.value+"&date="+addExercise.elements.date.value;
if(addExercise.elements.lbsOr.checked){
holder += "&lbsOr=1"; //bool check again
}
else{
holder += "&lbsOr=0";
}
request.open("GET", "/insert?" + holder, true); //Open the get request for asynchronous with the holder url packed
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.addEventListener('load', function(){
if(request.status >= 200 && request.status < 400){
var response = JSON.parse(request.responseText);
var id = response.inserted;
//prepping for table fill
var table = document.getElementById("exerciseTable");
var row = table.insertRow(1);
//creating cells and appending them to the rows to match the headers
var exerName = document.createElement('td');
exerName.textContent = document.getElementById('exercise').value;
row.appendChild(exerName);
var repCount = document.createElement('td');
repCount.textContent = document.getElementById('reps').value;
row.appendChild(repCount);
var weightAmount = document.createElement('td');
weightAmount.textContent = document.getElementById('weight').value;
row.appendChild(weightAmount);
var completion = document.createElement('td');
completion.textContent = document.getElementById('date').value;
row.appendChild(completion);
var unitChecker = document.createElement('td');
if(addExercise.elements.lbsOr.checked){ //once again the bool strikes comparing, you guessed it, lbs or kg
unitChecker.textContent = "lbs";
}
else{
unitChecker.textContent = "kg";
}
row.appendChild(unitChecker);
//adding the up date and delete buttons with DOM for each row
var yupDate = document.createElement('td');
var updateDataLink = document.createElement('a');
updateDataLink.setAttribute('href','/entryEdit?id=' + id);
var updateButton = document.createElement('input');
updateButton.setAttribute('value','Edit');
updateButton.setAttribute('type','button');
updateDataLink.appendChild(updateButton);
yupDate.appendChild(updateDataLink);
row.appendChild(yupDate);
var deleteCell = document.createElement('td');
var deleteButton = document.createElement('input');
deleteButton.setAttribute('type','button');
deleteButton.setAttribute('name','delete');
deleteButton.setAttribute('value','Delete');
deleteButton.setAttribute('onClick', 'deleteData("dataTable",' + id +')');//calls deleteData function with ID as a param
var deleteHidden = document.createElement('input');
deleteHidden.setAttribute('type','hidden'); //those hidden attributes though
deleteHidden.setAttribute('id', 'delete' + id);
deleteCell.appendChild(deleteButton);
deleteCell.appendChild(deleteHidden);
row.appendChild(deleteCell);
}
else {
console.log("error");
}
});
request.send(null);
event.preventDefault(); //no refreshes!
});
the server side database manipulation code
app.get('/insert',function(req,res,next){
var context = {};
pool.query("INSERT INTO `workouts` (`name`, `reps`, `weight`, `date`, `lbs`) VALUES (?, ?, ?, ?, ?)",
[req.query.exercise,
req.query.reps,
req.query.weight,
req.query.date,
req.query.lbsOr],
function(err, res){
if(err){
next(err);
return;
}
context.inserted = res.insertId;
res.send(JSON.stringify(context));
});
});
the Html code
<h1>Please add an exercise!</h1>
<form id="addExercise">
Exercise:
<input type="text" name="exercise" id="exercise"><br>
Reps:
<input type="number" name="reps" id="reps "min="1"><br>
Weight:
<input type="number" name="weight" id="weight "min="1"><br>
Date:
<input type="date" name="date" id="date"><br>
Check for Lbs:
<input type="checkbox" name="lbsOr" id="lbsOr"><br>
<input type="submit" name="Add Exercise" value = "Add Exercise" id="addExerciseButton">
</form><br>
<!-- table with permanent headers and then parses the "results " that get passed to this page by one of the many functions-->
<table id="exerciseTable">
<tr>
<th>Name</th>
<th>Reps</th>
<th>Weight</th>
<th>Date</th>
<th>Unit</th>
<th>Update</th>
<th>Delete</th>
</tr>
{{#if results}}
{{#each results}}
<tr>
<td>{{this.name}}</td>
<td>{{this.reps}}</td>
<td>{{this.weight}}</td>
<td>{{this.date}}</td>
<td>{{this.lbs}}</td>
<td><input type="button" value="Update"></td>
<td>
<input type="button" name="delete" value="Delete" onClick="deleteData('dataTable',{{this.id}})">
<input type="hidden" id="delete{{this.id}}">
</td>
</tr>
{{/each}}
{{/if}}
</table>
<script src="./java.js"></script>
any help with this is greatly appreciated, let me know if you guys need more code, I'm new to the whole Stack overflow thing.
I solved it!
` function(err, res){
if(err){
next(err);
return;
}
context.inserted = res.insertId;
res.send(JSON.stringify(context));
});`
should be'
` function(err, result){
if(err){
next(err);
return;
}
context.inserted = result.insertId;
res.send(JSON.stringify(context));
});`
I was double defining res, which would throw the error.
I have been given a code to modify for database records on a website using ajax.
I have the function correctly querying data but the table displayed does not get any of the records displayed with in it. I have code of the functions and the html below.
Please see this link of current version: http://www.eng.nene.ac.uk/~10406206/CSY2028/Ajax/Ajax.html
Function of loadrecords with a callback not sure why a callback is used
<script language="Javascript">
var xmlHttpReq = false;
var xmlHttpReq2 = false;
var xmlHttpReq3 = false;
function loadDatabaseRecordsCallback ()
{
if (xmlHttpReq.readyState == 4)
{
alert ("From Server (Load Records):List.php" + xmlHttpReq.responseText);
var record = xmlHttpReq.responseXML.getElementsByTagName('record');
var s = "";
for (var i = 0; i < record.length; i ++)
{
var rec = record[i];
var id = rec.getElementsByTagName("ID")[0].firstChild.data;
var carname = rec.getElementsByTagName("CARNAME")[0].firstChild.data;
var fueltype = rec.getElementsByTagName("FUELTYPE")[0].firstChild.data;
var transmission = rec.getElementsByTagName("TRANSMISSION")[0].firstChild.data;
var enginesize = rec.getElementsByTagName("ENGINESIZE")[0].firstChild.data;
var doors = rec.getElementsByTagName("DOORS")[0].firstChild.data;
var total = rec.getElementsByTagName("TOTAL")[0].firstChild.data;
var available = rec.getElementsByTagName("AVAILABLE")[0].firstChild.data;
appendRecord (id, carname, fueltype, transmission, enginesize, doors, total, available);
}
}
}
function loadDatabaseRecords ()
{
// Mozilla/Safari
if (window.XMLHttpRequest)
{
xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject)
{
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
alert ("To Server (Load Records): List.php");
xmlHttpReq.open('GET', "List.php", true);
xmlHttpReq.onreadystatechange = loadDatabaseRecordsCallback;
xmlHttpReq.send(null);
}
on the same page as the function is the table which is below
<body>
<form name="f1">
<input value="Load Database" type="button" onclick='JavaScript:loadDatabaseRecords()'></p>
</form>
<table id="DBTable" border="2">
<tr>
<td width="20">ID</td>
<td width="100">Car Name</td>
<td width="100">Fuel Type</td>
<td width="100">Transmission</td>
<td width="80">Engine size</td>
<td width="20">Doors</td>
<td width="20">Total</td>
<td width="20">Available</td>
</tr>
<form name="myform">
<tr>
<td><input type="text" name="id"></td>
<td><input type="text" name="carname"></td>
<td><input type="text" name="fueltype"></td>
<td><input type="text" name="transmission"></td>
<td><input type="text" name="enginesize"></td>
<td><input type="text" name="doors"></td>
<td><input type="text" name="total"></td>
<td><input type="text" name="available"></td>
<td colspan="2"><input type="button" value="add" onClick="JavaScript:addNewRecord()"></td>
<td colspan="2"><input type="checkbox" value="update" onClick="JavaScript:updateRecord()"></td>
<td colspan="2"><input type="checkbox" value="delete" onClick="JavaScript:deleteRecord()"></td>
</tr>
</form>
</table>
</body>
The function calls the List.php which is coded as follows
<?php
$link = mysql_connect ("194.81.104.22", "********", "*****");
mysql_select_db ("*******");
$query = "SELECT * from XYZ";
$result = mysql_query ($query);
for ($i = 0; $i < mysql_num_rows ($result); $i ++)
{
$row = mysql_fetch_object ($result);
print "<b>Car Name:</b> <i>$row->CARNAME</i><br>";
print "<b>Fuel Type:</b> <i>$row->FUELTYPE</i><br>";
print "<b>Transmission:</b> <i>$row->TRANSMISSION</i><br>";
print "<b>Total:</b> <i>$row->TOTAL</i><br>";
print "<b>Available:</b> <i>$row->AVAILABLE</i><br><br>";
}
mysql_close ($link);
?>
So, if you have seen the website you will see that you press the load database button and a box appears with all the database entries. However, once you press enter the table on the page remains empty.
My question is why?
can you explain to me where the problem is?
New to Ajax and apologies if I broke rules on posts it's my first one.
I am not clear with php, but I remember from my asp + ajax experiences:
You bring data back to your browser, but you should "re-paint" the page - you can do this in javascript, or may-be PHP has some ready solutions for this.
When you validated your method appendRecord receive valid values - find your table (DBTable) with javascript by id, and update the values of the row / columns by your record.
I'd recommend you to take a look on http://www.w3schools.com/php/php_ajax_database.asp
You bring data back to your browser, but you should "re-paint" the page - you can do this in javascript, or may-be PHP has some ready solutions for this.
When you validated your method appendRecord receive valid values - find your table (DBTable) with javascript by id, and update the values of the row / columns by your record.
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>