Issue calling http request with AJax on 3 different html pages - javascript

//home html
<body>
<h2>Search Data from NYC Open Data Site</h2>
<h3>Choose One Dataset Below to Start Searching</h3>
<div>
<label class="datasets">Data Sets:</label> <br>
<input type="radio" id="data1" name="dataset" value="data1" required>
<label>Data1</label><br>
<input type="radio" id="data2" name="dataset" value="data2" required>
<label>Data2</label><br>
<input type="radio" id="data3" name="dataset" value="data3" required>
<label>Data3</label><br>
</div><br>
<h3 id="searchvalues"></h3>
<br>
<table id="searchresults"></table>
</body>
////1st html with search field and 2nd and 3rd as the same
`
<table>
<tr><td>ID</td><td><input type="text" size="20" id="idnumber"></td></tr>
<tr><td>Year</td><td><input type="text" size="20" id="year"></td></tr>
</table>
`I'm doing a program with 3 different html pages to search the data using Json link. I have 3 radio buttons which will be called on change to 3 separate html pages on my home html. But when I click on radio 1 , I only get the contents of one html no matter which radio button I click, eg- when I click on 1st radio button , instead of getting data3.html, I still get the contents of data1.html and no search data is appearing. I just started learning Ajax and Json 2 weeks ago. Any help would be much appreciated.
var xhr;
var r;
var asynchrequest;
var radioChoices;
window.addEventListener("load", registerListeners);
function registerListeners() {
radioChoices = document.getElementById("data1");
radioChoices = addEventListener("change", function () { getContent("Data1.html"); }, false);
radioChoices = document.getElementById("data2");
radioChoices = addEventListener("change", function () { getContent("Data2.html"); }, false);
radioChoices = document.getElementById("data3");
radioChoices = addEventListener("change", function () { getContent("Data3.html"); }, false);
}
function getContent(infopage) {
asynchrequest = new XMLHttpRequest(); //step 1
asynchrequest.open("GET", infopage, true); //step 2
asynchrequest.onreadystatechange = function () { //step 3
if (asynchrequest.readyState == 4 && asynchrequest.status == 200) {
document.getElementById("searchvalues").innerHTML = asynchrequest.responseText;
}
};
asynchrequest.send(); //step 4
}
function loadData1() {
//event listener
document.getElementById("idnumber").addEventListener("keyup", function () { searchIDNumber(this.value); }, false);
document.getElementById("year").addEventListener("keyup", function () { searchYear(this.value); }, false);
xhr = new XMLHttpRequest();
xhr.open("GET", "https://data.cityofnewyork.us/resource/4d7f-74pe.json", true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
r = JSON.parse(xhr.responseText);
//displayData(r);
}
};
xhr.send();
}
function searchIDNumber(idnumber) {
//var r=JSON.parse(xhr.responseText);
document.getElementById("searchvalues").innerHTML = "Search by ID Number" + "<br>";
//structure table
var output = "<tr><th> ID </th><th> Fiscal Year </th><th> Organization Name </th><th> Status </th><th> Amount </th></tr>";
var searchid;
for (var i = 0; i < r.length; i++) {
var obj = r[i];
searchid = obj.mocs_id; // convert id to string from number value
if (searchid.startsWith(idnumber)) {
output += "<tr><td>";
output += obj.mocs_id;
output += "</td><td>";
output += obj.fiscal_year;
output += "</td><td>";
output += obj.legal_name_of_organization;
output += "</td><td>";
output += obj.status;
output += "</td><td>";
output += obj.amount;
}
}
document.getElementById("searchresults").innerHTML = output;
}
function searchYear(year) {
//var r=JSON.parse(xhr.responseText);
document.getElementById("searchvalues").innerHTML = "Search by Year" + "<br>";
//structure table
var output = "<tr><th> ID </th><th> Fiscal Year </th><th> Organization Name </th><th> Status </th><th> Amount </th></tr>";
var searchid;
for (var i = 0; i < r.length; i++) {
var obj = r[i];
searchid = obj.fiscal_year; // convert id to string from number value
if (searchid.startsWith(year)) {
output += "<tr><td>";
output += obj.mocs_id;
output += "</td><td>";
output += obj.fiscal_year;
output += "</td><td>";
output += obj.legal_name_of_organization;
output += "</td><td>";
output += obj.status;
output += "</td><td>";
output += obj.amount;
}
}
document.getElementById("searchresults").innerHTML = output;
}

Related

How to save radio buttons to local storage

i have a quiz with radio buttons ,sow i have to save the answears on my local storge ,but im stuck i don t know what else to do,im learnig sow dont hate me pls,tnx
This is my code sow far
<form id="quiz"> </form>
<script>
let object;
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "quiz.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object = JSON.parse(this.response);
console.log(object)
}
let json = object
let quiz = document.getElementById("quiz");
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i++) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html += "<div><h2>Question " + (i + 1) + ": " + questionItem.question + "</h2></div>";
html += "<div>";
for (let i = 0; i < questionItem.options.length; i++) {
html += "<div >";
html += "<input type=\"radio\" id=\"q\" checked=\"checked\" name=\"qzz" + key + "_option\" value=\"" + questionItem.options[i] + "\">" + questionItem.options[i] ;
html += "</div>";
}
quiz.innerHTML += html;
}
quiz.innerHTML += "<input type=\"submit\" value=\"submit\">";
function save() {
var g1 = document.querySelector('input[type="radio]');
g1 = (g1) ? g1.value : '';
localStorage.setItem("g1", g1);
}
});
You can simplify your AJAX dialog by using fetch() instead of new XMLHttpRequest();. I straightened out a few things in your code (also see the initial remarks in #brianagulo's answer) and prepared a little set of sample data to demonstrate the whole functionality of the quiz. The jsonplaceholder.typicode.com url only serves as a working json-server endpoint. The received data is actually ignored here.
In your "production version" you will need to un-comment the line:
localStorage.setItem("quiz",JSON.stringify(ans))
The checked answers where collected in an object doing
[...document.querySelectorAll('input[type=radio]:checked')].reduce((a,{name,value}) =>(a[name]=value,a), {});
This
collects all checked radio button inputs with (document.querySelectorAll('input[type=radio]:checked')),
converts the collection of DOM elements into a proper array (with [... ])and eventually
reduce()-s its elements into an object where the element names are the property names and the (input-)element values are the property values.
And also please note that you can only store strings in local storage. Therefore I converted the ans object into a JSON string before using it in the .setItem() method.
const Q = {
quiz: [{
question: "Where was the Boston tea party?",
options: ["New York", "Detroit", "Boston", "Reno"]
}, {
question: "Where would you find Venice Beach?",
options: ["Detroit", "Venice", "Paris", "Los Angeles"]
}, {
question: "Where would you find Queens?",
options: ["London", "Paris", "Stockholm", "New York"]
}, {
question: "Where is Greenwich Village?",
options: ["London", "Paris", "Stockholm", "New York"]
}, {
question: "Where would you find the Gateway Arch?",
options: ["St. Quentin", "St. Louis", "St. Anton", "San Francisco"]
}]
}, quiz = document.getElementById("quiz");
var url = "quiz.json";
// in your productive version: comment out the following line
url = "https://jsonplaceholder.typicode.com/users/7"; // functioning test URL for fetch
function save(ev) {
ev.preventDefault();
const ans=[...document.querySelectorAll('input[type=radio]:checked')].reduce((a,{name,value}) =>(a[name]=value,a), {});
// in Stackoverflow snippets you cannot use local storage, so here is console.log instead:
console.log(ans);
// in your productive version: un-comment the following line
// localStorage.setItem("quiz",JSON.stringify(ans))
}
fetch(url).then(r => r.json()).then(object => {
// remove the following line:
object = Q; // use the static quiz from defined in Q instead ...
let json = object
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i++) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html += "<div><h2>Question " + (i + 1) + ": " + questionItem.question + "</h2></div>";
html += "<div>";
for (let i = 0; i < questionItem.options.length; i++) {
html += "<label>";
html += "<input type=\"radio\" id=\"q\" name=\"qzz" + key + "_option\" value=\"" + questionItem.options[i] + "\"> " + questionItem.options[i];
html += "</label><br>";
}
quiz.innerHTML += html;
}
quiz.innerHTML += "<input type=\"submit\" value=\"submit\">";
quiz.onsubmit=save;
});
<form id="quiz"> </form>
There is a typo on your save function. You are missing a quote after radio:
var g1 = document.querySelector('input[type="radio"]');
Also, your question is confusing but if what you are trying to do is get whether the radio is checked or not you must access the checked property and save that to localStorage. And if you want to save the state for all of the buttons then you should use querySelectorAll and save them that way instead. Example below of accessing a single input's checked value:
function save() {
// you can access it directly on this line
var g1 = document.querySelector('input[type="radio]').checked;
localStorage.setItem("g1", g1);
}
For saving them all
Lastly, it seems you are not actually calling the save() function. If your intention is to have the radios checked state saved to localStorage on click you may want to add an event to the submit button. For example:
<form id="quiz"> </form>
<script>
let object;
let httpRequest = new XMLHttpRequest();
httpRequest.open("GET", "quiz.json", true);
httpRequest.send();
httpRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
object = JSON.parse(this.response);
console.log(object)
}
let json = object
let quiz = document.getElementById("quiz");
let keyList = Object.keys(json.quiz);
for (let i = 0; i < keyList.length; i++) {
let key = keyList[i];
let questionItem = json.quiz[key];
let html = "<div>";
html += "<div><h2>Question " + (i + 1) + ": " + questionItem.question + "</h2></div>";
html += "<div>";
for (let i = 0; i < questionItem.options.length; i++) {
html += "<div >";
html += "<input type=\"radio\" id=\"q\" checked=\"checked\" name=\"qzz" + key + "_option\" value=\"" + questionItem.options[i] + "\">" + questionItem.options[i] ;
html += "</div>";
}
quiz.innerHTML += html;
}
quiz.innerHTML += "<input type=\"submit\" value=\"submit\">";
function save() {
// you can access it directly on this line
var g1 = document.querySelector('input[type="radio]').checked;
localStorage.setItem("g1", g1);
}
let submitButton = document.querySelector('input[type="submit"]');
submitButton.onclick = (event) => {
/* this prevents page refresh and submission to the backend which is a form default */
event.preventDefault();
// then we call the save function here
save();
};
});
If this was helpful please consider selecting as the answer

my input return me undefined even though the data is catch. using CRUD js

<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries');
this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "popultns" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var pop = el2.value;
if (country2)
{ // Add the new value
loadTableData.push(country2.trim() );
// Reset input value
el.value = '';
//el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
the image is the ui tht im working for the function
I'm supposed to auto-generate the table based on the data available from my main.js script which is in JSon format. There is no problem with the data loading since the data can be display in my html file. However, the problem comes whn my data is returned undefined on my auto generated table whn i click the 'add' button to update the data in the table. Whn i click in the edit button, the data is get correctly. only whn the display, it returns me undefined.
i know how alrdy.
here i attach the code & sample of the data i hv done.
hopefully this would help fresh grad like me who hv trouble in undrsntdng CRUD
<html>
<head>
<meta charset="UTF-8">
<title>Countries CRUD</title>
<style>
input[type='submit'], button, [aria-label]{
cursor: pointer;
}
#spoiler{
display: none;
}
</style>
</head>
<body>
<form action="javascript:void(0);" method="POST" onsubmit="app.Add()">
<input type="text" id="add-name" placeholder="New country ">
<input type="number" id="add-popu" placeholder="New population">
<input type="submit" value="Add">
</form>
<div id="spoiler" role="aria-hidden">
<form action="javascript:void(0);" method="POST" id="saveEdit">
<input type="text" id="edit-name">
<input type="text" id="edit-popu">
<input type="submit" value="Ok" /> <a onclick="CloseInput()" aria-label="Close">✖</a>
</form>
</div>
<p id="counter"></p>
<table>
<tr>
<th>Country</th>
<th>Population</th>
</tr>
<tbody id="countries"></tbody>
<tbody id="popultns"></tbody>
</table>
<script type="text/javascript" src="main.js"></script>
<script>
var app = new function()
{ this.el = document.getElementById('countries' && 'popultns');
//this.el = document.getElementById('popultns');
let loadTableData = data2;
this.Count = function(data)
{ var el = document.getElementById('counter');
var name = 'country2';
var pop = 'popu2'
if (data)
{ if (data > 1)
{ name = 'countries' ;
pop = "populations" ;
}
el.innerHTML = data + ' ' + name + ' ' + pop ;
}
else
{ el.innerHTML = 'No ' + name + ' ' + pop ; }
};
this.FetchAll = function()
{ var data = '';
if (loadTableData.length > 0)
{ for (i = 0; i < loadTableData.length; i++)
{ data += '<tr>';
data += '<td>' + loadTableData[i].country + '</td>';
data += '<td>' + loadTableData[i].population + '</td>';
data += '<td><button onclick="app.Edit(' + i + ')">Edit</button></td>';
data += '<td><button onclick="app.Delete(' + i + ')">Delete</button></td>';
data += '</tr>';
}
}
this.Count(loadTableData.length);
return this.el.innerHTML = data;
};
this.Add = function ()
{ el = document.getElementById('add-name');
el2 = document.getElementById('add-popu');
// Get the value
var country2 = el.value;
var popltn = el2.value;
if (country2 && popltn )
{ // Add the new value
//loadTableData.push(country2.trim() );
loadTableData.push({country: country2, population:popltn});
// Reset input value
el.value = '';
el2.value = '';
// Dislay the new list
this.FetchAll();
}
};
this.Edit = function (item)
{ var el3 = document.getElementById('edit-name');
var el4 = document.getElementById('edit-popu');
// Display value in the field
let index = item;
el3.value = loadTableData[index].country;
el4.value = loadTableData[index].population;
// Display fields
document.getElementById('spoiler').style.display = 'block';
self = this;
document.getElementById('saveEdit').onsubmit = function()
{
// Get value
var country2 = el3.value;
var popltn = el4.value;
//console.log({country2, pop});
if (country2 || pop)
//console.log(country2);
{ // Edit value (strt,del,replace)
console.log(country2,popltn);
console.log(index, 1,({country2,popltn}));
//update array
loadTableData[index].country = el3.value;
loadTableData[index].population = el4.value;
//self.loadTableData.splice(index, 1,({country2,popltn}));
//console.log(index, 1, pop.trim());
//self.loadTableData.splice(index, 1, pop.trim());
// Display the new list
self.FetchAll();
// Hide fields
CloseInput();
}
}
};
this.Delete = function (item)
{
// Delete the current row
loadTableData.splice(item, 1);
// Display the new list
this.FetchAll();
};
}
app.FetchAll();
function CloseInput()
{ document.getElementById('spoiler').style.display = 'none';}
</script>
</body>
</html>

How to parse XML using AJAX in html?

I'm trying to parse XML by using AJAX. However there were a few errors which i got saying my "html is not defined"
Basically what I want to do is to parse a specific amount of data from my XML codes and display it using HTML webpage .
The below is the list of bugs in console when I tried to run the script
at displayCountrylist (test2.html:136)
at handleStatusSuccess (test2.html:61)
at readyStateChangeHandler (test2.html:32)
at XMLHttpRequest.xhttp.onreadystatechange (test2.html:16)
I tried to do everything to debug but still failed. Any one help please?
<html>
<script>
function makeAjaxQueryCountrylist()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
readyStateChangeHandler(xhttp);
};
xhttp.open("GET", "A3_CtryData_dtd_Sample.xml", true);
xhttp.send();
}
function readyStateChangeHandler(xhttp)
{
if (xhttp.readyState == 4)
{
if(xhttp.status == 200)
{
handleStatusSuccess(xhttp);
}else
{
handleStatusFailure(xhttp);
}
}
}
function handleStatusFailure(xhttp){
var displayDiv = document.getElementById("display");
displayDiv.innerHTML = "XMLHttpRequest failed: status " + xhttp.status;
}
function handleStatusSuccess(xhttp)
{
var xml = xhttp.responseXML;
var countrylistObj = parseXMLCountrylist(xml);
displayCountrylist(countrylistObj);
}
function parseXMLCountrylist(xml)
{
var countrylistObj = {};
var countrylistElement = xml.getElementsByTagName("CountryList")[0];
var recordElementList = countrylistElement.getElementsByTagName("CountryRecord");
countrylistObj.recordList = parseRecordElementList(recordElementList);
return countrylistObj;
}
function parseRecordElementList(recordElementList)
{
var recordList = [];
for(var i=0; i < recordElementList.length; i++)
{
var recordElement = recordElementList[i];
var recordObj = parseRecordElement(recordElement);
recordList.push(recordObj);
}
return recordList;
}
function parseRecordElement(recordElement)
{
var recordObj = {};
var countrycodeElement = recordElement.getElementsByTagName("country-code")[0];
recordObj.countrycode = Number(countrycodeElement.textContent);
var nameElement = recordElement.getElementsByTagName("name")[0];
recordObj.name = nameElement.textContent;
var alpha2Element = recordElement.getElementsByTagName("alpha-2")[0];
recordObj.alpha2 = alpha2Element.textContent;
var alpha3Element = recordElement.getElementsByTagName("alpha-3")[0];
recordObj.alpha3 = alpha3Element.textContent;
var capitalcityElement = recordElement.getElementsByTagName("capital-city")[0];
recordObj.capitalcity = capitalcityElement.textContent;
return recordObj;
}
function displayCountrylist(countrylistObj)
{
for(var i=0; i < countrylistObj.recordList.length; i++)
{
var recordObj = countrylistObj.recordList[i];
html += "country-code: " + recordObj.countrycode;
html += "<br />";
html += "name: " + recordObj.name;
html += "<br />";
html += "alpha-2: " + recordObj.alpha2;
html += "<br />";
html += "alpha-3: " + recordObj.alpha3;
html += "<br />";
html += "capital-city: " + recordObj.capitalcity;
html += "<br />";
}
var displayDiv = document.getElementById("display1");
displayDiv.innerHTML = html;
}
</script>
<body>
<button onClick="makeAjaxQueryCountrylist()"> Region Info I (Format: region-fmt-1.xsl)</button>
<br /><br />
<div id="display1">
</div>
</body>
</html>
There isn't any problem with my XML codes so it has to be some error from here.
You got that error html is not defined because you are using html variable without declaring it. So, before the line
html += "country-code: " + recordObj.countrycode;
you have to write
let html = '';

Javascript: Javascript ignores the elements generated by itself

I have this javascript function that generates new selects with IDs:
function generateChild(root, categories){
++counter;
var appendid = "id='selectCategory_".concat(counter);
var coma = "'";
var mayorque = "'>";
var appendcoma = appendid.concat(coma);
var select ="<div class='selectContainer'".concat(appendcoma);
var close = "><select ";
var cerrar = select.concat(close);
var appendidselect = cerrar.concat(appendid);
var html = appendidselect.concat(mayorque);
for (var i = 0; i < categories.length; i++) {
html += "<option value='" + categories[i] + "'>" + categories[i] + "</option>";
}
html += '</select></div>';
// ---------------------------
// ---------------------------
// create an element from the html string
// ---------------------------
var tplt = root.createElement('template');
tplt.innerHTML = html;
var el = tplt.content.firstChild;
// ---------------------------
// ---------------------------
// attach the change handler
// ---------------------------
el.firstChild.addEventListener("change", handle_onChange);
// ---------------------------
return el;
}
}
And then this function to search for the last dropdown that didn't have a blank space on it, and save it in a hidden input for later use:
if(this.value == ' '){
for (var i = counter - 1 ; i >= 0 ; --i){
var string = i.toString();
var selectid = "selectCategory_".concat(string);
if(document.getElementById(selectid)){
document.getElementById("category").value = document.getElementById(selectid).value;
break;
}
}
}
else{
var lastselectedvalue = this.value;
document.getElementById("category").value = this.value;
}
This works well with the first dropdown, which is already in the code:
<input type ="hidden" name="category" id = "category" value="">
<div id="category0" class="selectContainer">
<select id="selectCategory_0">
<option>something</option>
<option>something else</option>
</select>
</div>
But never works with the other dropdowns, it always returns undefined.

All javascript functions coming up undefined from html

I had majority of these functions working and now when i restarted my program they are saying undefined functions through chrome. Not sure the exact problem, im sure im missing something somewhere but its not coming up through eclipse. REALLY NEED HELP !!!! cant figure out the exact location or i would have shortened the files but i felt more is better than less in this instance where i cant find out where the code is breaking. Thank you all
HTML FILE
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="layout.css">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Manager Menu</title>
</head>
<body>
<div id = "header">
Welcome to the employee database;
</div>
<div id = "login">
Welcome <label id="welcomeLabel"></label>
<form action="http://localhost/Employee_12_14_13/login.html">
<input type="submit" value="Logout">
</form>
</div>
<div id = "buttons">
<br/><input type="submit" value="Create Group" onclick='createGroup()'>
<br/><input type="submit" value="Edit Employee" onclick='editEmployee()'>
<br/><input type="submit" value="Search for Employee" onclick='search()'>
<br/><input type="submit" value="View all employees" onclick='viewAll()'>
<br/><input type="submit" value="Delete Group" onclick='deleteGroup()'>
<br/><input type="submit" value="View all no group" onclick='viewNoGroup()'>
</div>
<div id ="createGroup" style="display:none">
<br/>Enter name of Group: <input type ="text" name="newGroup" id="newGroup">
<input type="submit" value="Enter">
</div>
<div id ="deleteGroup" style="display:none">
<br/>Enter name of Group: <input type ="text" name="newGroup" id="newGroup">
<input type="submit" value="Enter">
</div>
<div id ="Search" style="display:none">
<br/>Employee Email: <input type ="text" name ="toFind" id ="toFind">
<input type="submit" value="Enter" onclick='searchFor()'>
</div><div id ="editPersonalInfo" style="display:none">
<br/>Employee Email: <input type ="text" name="username" id="user">
<br/>Name: <input type="text" name ="name" id="name">
<input type="submit" value="Edit Name" onclick='editName()'>
<br/>Email address: <input type="text" name ="email" id="email">
<input type="submit" value="Edit Email" onclick='editEmail()'>
<br/>Password: <input type="password" name ="pass" id="pass">
<input type="submit" value="Edit Password" onclick='editPass()'>
<br/>Phone number: <input type="text" name ="phone" id="phone">
<input type="submit" value="Edit Phone" onclick='editPhone()'>
<br/>Programming Language: <input type="text" name ="username" id="user">
<form action="http://localhost/Employee_12_14_13/login.html">
<input type="submit" value="Logout">
</form>
<form action="http://localhost/Employee_12_14_13/menu.html">
<input type="submit" value="MainMenu">
</form>
</div>
<div id="employeePersonalInfo" style="display:none">
<br/>Id: <label id="id"></label>
<br/>Name: <label id="name"></label>
<br/>Email address: <label id="email"></label>
<br/>Phone number: <label id="phone"></label>
<form action="http://localhost/Employee_12_14_13/login.html">
<input type="submit" value="Return">
</form>
<form action="http://localhost/Employee_12_14_13/menu.html">
<input type="submit" value="Menu">
</form>
</div>
<div id="viewAllTable" style="border: 0px solid black"></div>
<div id="viewAllNoGroup" style="border: 0px solid black"></div>
<div id="viewAllInGroup" style="border: 0px solid black"></div>
<div id="searchTable" style="border: 0px solid black"></div>
</body>
<script src="./JS/managerMenu.js"></script>
</html>
JS
function GetRequest() {
var url = location.search;
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest = (strs[i].split("=")[1]);
}
}
return theRequest;
}
function changeLabel()
{
document.getElementById("welcomeLabel").innerHTML = GetRequest();
}
function createGroup()
{
}
function deleteGroup()
{
setAllInvis();
deleteGroupServlet(GetRequest());
}
function searchFor()
{
setAllInvis();
changeLabel();
callServlet(document.getElementById("toFind").value);
}
function setAllInvis()
{
document.getElementById("viewAllTable").style.display="none";
document.getElementById("viewAllInGroup").style.display="none";
document.getElementById("viewAllNoGroup").style.display="none";
document.getElementById("searchTable").style.display="none";
document.getElementById("createGroup").style.display="none";
document.getElementById("editPersonalInfo").style.display="none";
document.getElementById("Search").style.display="none";
document.getElementById("deleteGroup").style.display="none";
document.getElementById("editPersonalInfo").style.display="none";
document.getElementById("employeePersonalInfo").style.display="none";
}
function search()
{
setAllInvis();
document.getElementById("Search").style.display="block";
}
function editEmployee()
{
setAllInvis();
document.getElementById("editPersonalInfo").style.display="block";
}
function editName()
{
editServlet("name",document.getElementById("user").value,document.getElementById("name").value);
}
function editEmail()
{
editServlet("email",document.getElementById("user").value,document.getElementById("email").value);
}
function editGroup()
{
editServlet("group"),document.getElementById("user").value,document.getElementById("group").value;
}
function editPass()
{
editServlet("pass",document.getElementById("user").value,document.getElementById("pass").value);
}
function editPhone()
{
editServlet("phone",document.getElementById("user").value,document.getElementById("phone").value);
}
function viewEmployee()
{
viewEmployee(document.getElementById("toFind").value);
}
function viewNoGroup()
{
setAllInvis();
var http = new getXMLHttpRequestObject();
var url = "viewNoGroupServlet";
alert("viewNoGroup");
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
var jsonObj = JSON.parse(http.responseText);
viewNoGroupTable(jsonObj);
};
http.send();
}
function searchNoGroup()
{
viewNoGroup();
}
function next(){
setAllInvis();
var select = document.getElementById("managerMenu");
var index = select.selectedIndex;
var menuOption = select.options[index].value;
var username = GetRequest();
if(menuOption=="Search by email address"){
document.getElementById("username").value = "";
document.getElementById("message").style.display="none";
document.getElementById("search").style.display="block";
document.getElementById("viewAllTable").style.display="none";
}
else if(menuOption=="View all"){
document.getElementById("search").style.display="none";
document.getElementById("searchTable").style.display="none";
document.getElementById("viewAllTable").style.display="block";
viewAll();
}
}
function validateLogin(){
var username = document.getElementById("username").value;
callServlet(username);
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function getXMLHttpRequestObject() {
var xmlhttp = 0;
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
// Opera 8.0+, Firefox, Chrome, Safari
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
function editServlet(toEdit,email,changeTo)
{
var parameters = "username="+email+"&toChange="+toEdit+"&changeTo="+changeTo;
var http = new getXMLHttpRequestObject();
var url = "editInformationServlet";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.send(parameters);
}
function callServlet(username){
var http = new getXMLHttpRequestObject();
var url = "Menu";
var parameters = "username=" + username;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
var jsonObj = JSON.parse(http.responseText);
searchTable(jsonObj);
}
http.send(parameters);
}
function deleteGroupServlet(username){
var http = new getXMLHttpRequestObject();
var url = "deleteGroupServlet";
var parameters = "username="+username;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.send(parameters);
}
function addToGroup()
{
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
var email=data[3];
alert(email);
addToGroupServlet(email);
}
}
function addToGroupServlet(email);
{
var parameters = "username="+email+"&managerEmail="+GetRequest();
var http = new getXMLHttpRequestObject();
var url = "addToGroupServlet";
alert("In add to group");
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {// Handler function for call back on
if(http.readyState==4){
alert("addedToGroup");
ViewAllServlet();
}
http.send(parameters);
}
}
function deleteFromGroup(){
var table = document.getElementsByTagName("table")[0];
var tbody = table.getElementsByTagName("tbody")[0];
tbody.onclick = function (e) {
e = e || window.event;
var data = [];
var target = e.srcElement || e.target;
while (target && target.nodeName !== "TR") {
target = target.parentNode;
}
if (target) {
var cells = target.getElementsByTagName("td");
for (var i = 0; i < cells.length; i++) {
data.push(cells[i].innerHTML);
}
}
alert(data);
var email=data[3];
alert(email);
deleteFromGroupServlet(email);
}
}
function deleteFromGroupServlet(email)
{
var parameters = "username="+email;
var http = new getXMLHttpRequestObject();
var url = "deleteFromGroupServlet";
alert("In delete from group");
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {// Handler function for call back on
if(http.readyState==4){
alert("deletedFromGroup");
ViewAllServlet();
}
}
http.send(parameters);
}
function searchTable(jsonObj) {
var data = '';
data += '<table border=1><tbody><tr>';
data += '<th> ID </th>';
data += '<th> Name </th>';
data += '<th> Salary </th>';
data += '<th> Email address </th>';
data += '<th> Phone number </th>';
for (var i = 0; i < 1; i++) {
data += '<tr>';
data += '<td>' + jsonObj.id + '</td>';
data += '<td>' + jsonObj.name + '</td>';
data += '<td>' + jsonObj.salary + '</td>';
data += '<td>' + jsonObj.email + '</td>';
data += '<td>' + jsonObj.phone + '</td>';
data += '</tr>';
}
data += '</tbody><table>';
document.getElementById("searchTable").innerHTML = data;
}
function viewAll(){
ViewAllServlet();
}
function ViewAllServlet(){
var http = new getXMLHttpRequestObject();
var url = "viewAllServlet";
var email =GetRequest();
var parameters = "username="+email;
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {// Handler function for call back on
if(http.readyState==4){
var jsonObj = JSON.parse(http.responseText);
viewAllTable(jsonObj);
setAllInvis();
document.getElementById("viewAllTable").style.display="block";
}
http.send(parameters);
}
}
function viewNoGroupTable(jsonObj)
{
var data = '';
data += '<table border=1><tbody><tr>';
data += '<th> ID </th>';
data += '<th> Name </th>';
data += '<th> Salary </th>';
data += '<th> Email address </th>';
data += '<th> Phone number </th>';
for (var i = 0; i < jsonObj.length; i++) {
data += '<tr>';
//for (var j = 0; j < colMax; j++) {
data += '<td>' + jsonObj[i].id + '</td>';
data += '<td>' + jsonObj[i].name + '</td>';
data += '<td>' + jsonObj[i].salary + '</td>';
data += '<td>' + jsonObj[i].email + '</td>';
data += '<td>' + jsonObj[i].phone + '</td>';
data += '<td><input type="submit" onclick="addToGroup()" value = Add To Group></td>';
//}
data += '</tr>';
}
data += '</tbody><table>';
alert("creating table");
document.getElementById('viewAllNoGroup').innerHTML = data;
document.getElementById('viewAllNoGroup').style.display="block";
}
function viewAllTable(jsonObj) {
var data = '';
data += '<table border=1><tbody><tr>';
data += '<th> ID </th>';
data += '<th> Name </th>';
data += '<th> Salary </th>';
data += '<th> Email address </th>';
data += '<th> Phone number </th>';
for (var i = 0; i < jsonObj.length; i++) {
data += '<tr>';
//for (var j = 0; j < colMax; j++) {
data += '<td>' + jsonObj[i].id + '</td>';
data += '<td>' + jsonObj[i].name + '</td>';
data += '<td>' + jsonObj[i].salary + '</td>';
data += '<td>' + jsonObj[i].email + '</td>';
data += '<td>' + jsonObj[i].phone + '</td>';
data += '<td><input type="submit" onclick="deleteFromGroup()" value = "Delete from Group"></td>';
//}
data += '</tr>';
}
data += '</tbody><table>';
document.getElementById('viewAllTable').innerHTML = data;
}
Not sure the exact problem, im sure im missing something somewhere but its not coming up through eclipse. REALLY NEED HELP !!!! cant figure out the exact location or i would have shortened the files but i felt more is better than less in this instance where i cant find out where the code is breaking. Thank you all
You have an error in your code that i pointed,
You have defined function and ended it using ;
function addToGroupServlet(email);
change above to
function addToGroupServlet(email)
move your:
<script src="./JS/managerMenu.js"></script> tags to the <head> section
you have ended function by ;
function addToGroupServlet(email){
//....
}

Categories