I have this HTML file where if the user clicks on "View questions", it should display the parsed data that I receive. Right now I am working with a JSON test file. It displays the data fine, but I need to dynamically add checkboxes using Javascript for when the data is displayed. And when the user clicks on a checkbox, that data can be sent through Ajax to the backend. How can I achieve this? Any help would be appreciated. Thanks.
<button type=button class="lg=button" id="btn">View questions</button>
<p id="response"></p>
<script>
var resp = document.getElementById("response");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://learnwebcode.github.io/json-example/animals-1.json", true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
console.log(xhr.responseText);
var ourData = JSON.parse(xhr.responseText);
//console.log(ourData);
renderHTML(ourData);
}
}
xhr.send();
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + " that likes to eat ";
}
htmlString += '.</p>';
resp.insertAdjacentHTML('beforeend', htmlString);
}
</script>
It displays the data fine, but I need to dynamically add checkboxes using Javascript for when the data is displayed you need to put input type checkbox while rendering it
<input id="checkBox" type="checkbox">
You can add event listener to do any logic based on click event on those checkbox.
var resp = document.getElementById("response");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://learnwebcode.github.io/json-example/animals-1.json", true);
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
console.log(xhr.responseText);
var ourData = JSON.parse(xhr.responseText);
//console.log(ourData);
renderHTML(ourData);
}
}
xhr.send();
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p><input type='checkbox'>" + data[i].name + " is a " + data[i].species + " that likes to eat ";
}
htmlString += '.</p>';
resp.insertAdjacentHTML('beforeend', htmlString);
}
<button type=button class="lg=button" id="btn">View questions</button>
<p id="response"></p>
I am getting the below json response from the servelet for the ajax request but unable to convert the data into table and display it in jsp.
[{
"ordernumber": 123456,
"slotservice": "Collection ",
"deliverydate": "Jul 1, 2017"
}]
Below is my javascript which does the ajax request,
function addData(){
if(window.XMLHttpRequest) { //Assuming you're not on one of the old IEs.
var xhttp = new XMLHttpRequest();
xhttp.open("POST","Order",true);
var formData = new FormData(document.getElementById('orderform'));
xhttp.send(formData);
console.log('This is Ajax request to the order controller');
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && (xhttp.status == 200)) {
var myArr = JSON.parse(xhttp.responseText);
console.log(JSON.stringify(myArr));
var tr;
for (var i=0;i<myArr.length;i++){
tr = $('<tr/>');
tr.append("<td>"+myArr[i].ordernumber+ "</td>");
tr.append("<td>"+myArr[i].slotservice+ "</td>");
tr.append("<td>"+myArr[i].deliverydate+ "</td>");
$('ViewOrderResultContainer').append(tr);
console.log
}
}
}
}
else console.log('not working');
}
Below is the table defined in my index.jsp
<div id="divOrderResultContainer">
<table id="ViewOrderResultContainer" border=1>
<thead>
<tr>
<th>OrderNumber</th>
<th>ServiceType</th>
<th>DeliveryDate</th>
</tr>
</thead>
</table>
</div>
Can anyone explain me what i am doing wrong here and how can i get the expected results.
Edit 1: I have now updated my servlet like below but its still not printing the HTML table response in my jsp
function addData(){
if(window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (xhttp.readyState == 4 && (xhttp.status == 200)) {
var jsonorderdata = JSON.parse(xhttp.responseText);
for (x in jsonorderdata)
txt += "<tr><td>" + myObj[x].ordernumber+ "</td><td>" +
myObj[x].slotservice+ "</td><td>" + myObj[x].deliverydate+ "</td>"
"</tr>";
}
document.getElementById("ViewOrderResultContainer").innerHTML =
txt;
}
}
xhttp.open("POST","Order",true);
var formData = new FormData(document.getElementById('orderform'));
xhttp.send(formData);
}
else console.log('not working');
}
Additionally my javascript gives 304:not modified response in chrome , can anyone please help me on how to get the table in jsp.
You are missing selector in $('ViewOrderResultContainer').append(tr);. Add # to select an element by id
$('#ViewOrderResultContainer').append(tr);
I'm trying to GET from the url: http://redsox.tcs.auckland.ac.nz/BC/Open/Service.svc/booklist
Then parse this into JSON, send the JSON format into a table creating function showTable().
The html file:
<!DOCTYPE html>
<html>
<head>
<title>Online Shop</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
<script src="myscripts.js"></script>
</head>
<body>
<h1 id="mainheader">Boutique</h1>
<table id="menuTable" align="center">
<tr>
<td><button onclick="getResults()">Browse shop</button></td>
<td><button onclick="joinShop()">join the shop</button></td>
<td><button onclick="showComments()">Your comments</button></td>
</tr>
</table>
<hr></hr>
<div id="bodyDiv">
</div>
</body>
</html>
The relevant javascript:
function getResults(){ //gotta change it to take appended shit after ".svc/"
var uri = "http://redsox.tcs.auckland.ac.nz/BC/Open/Service.svc/booklist";
var xhr = new XMLHttpRequest();
xhr.open('GET', uri, true);
xhr.onload = function (){
var resp = JSON.parse(xhr.responseText);
showTable(resp.value);
}
xhr.send(null);
}
function showTable(item) {
var tableContent = "<tr class='orderTitle'><td>book id</td><td>book title</td></tr>\n"//creating unique table heading column
for(var i = 0; i < item.length; ++i) {
var record = item[i];
if (i & 1 == 1){
tableContent += "<tr class='orderOdd'>";
}
else { //even row
tableContent += "<tr class='orderEven'>";
}
tableContent += "<td>" + record.Id + "</td><td>" + record.Title + "</td></tr>\n"
}
document.getElementById("bodyDiv").innerHTML = tableContent;
}
<html>
<head>
</head>
<body>
<div id="content"></div>
<script>
function handleResponse(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.text should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" +item.volumeInfo.title+"<br>"+item.volumeInfo.imageLinks.thumbnail;
}
}
</script>
<script src="https://www.googleapis.com/books/v1/volumes/buc0AAAAMAAJ"></script>
</body>
</html>
Here I am Trying to Get Details of The Book Through Specific ID from the Google Books Please Help in JavaScript and JSON
You can get the information about a particular book by making xhr request. I have created a function which return title and thumbanil of particular Book ID:
function getBookDetails(id) {
var xmlhttp = new XMLHttpRequest();
var url = "https://www.googleapis.com/books/v1/volumes/" + id;
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var item = JSON.parse(xmlhttp.responseText);
document.getElementById("content").innerHTML += "<br>" + item.volumeInfo.title + "<br>" + "<img src=\""+item.volumeInfo.imageLinks.thumbnail+"\" >";
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
getBookDetails("buc0AAAAMAAJ");
Working Fiddle
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){
//....
}