Sorting the table data using Ajax - javascript

I want to sort the table data as alphabetical order. The HTML needs not to be reloaded again.
The JSON data hosted on an online server, The button can be added when clicking the table should be sorted automatically with the column "title" alphabetically.
$(document).ready(function() {
$.getJSON("my json file", function(data) {
var movie_data = '';
$.each(data.movies, function(key, value) {
movie_data += '<tr>';
movie_data += '<td>' + value.title + '</td>';
movie_data += '<td>' + value['imdb-id'] + '</td>';
movie_data += '<td>' + value.rank + '</td>';
movie_data += '<td>' + value.rating + '</td>';
movie_data += '<td>' + value['rating-count'] + '</td>';
movie_data += '<tr>';
});
$('#movie_table').append(movie_data);
});
});
<!DOCTYPE html>
<html>
<head>
<title>JSON data to HTML table</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-responsive">
<h1>TOP MOVIES</h1>
<br />
<table class="table table-bordered table-striped" id="movie_table">
<tr>
<th>Title</th>
<th>IMDB-ID</th>
<th>RANK</th>
<th>RATING</th>
<th>RATING-COUNT</th>
</tr>
</table>
</div>
</div>
</body>
</html>

I'd do something like this:
$(document).ready(function() {
var data = null;
$.getJSON("my json file", function(jsonData) {
data = jsonData.movies;
reloadTable();
});
$("#btn-sort").click(function() {
data.sort(function(a,b) {
return a.title < b.title ? -1 : 1;
});
reloadTable();
});
function reloadTable() {
var movie_data = '';
$.each(data.movies, function(key, value) {
movie_data += '<tr>';
movie_data += '<td>' + value.title + '</td>';
movie_data += '<td>' + value['imdb-id'] + '</td>';
movie_data += '<td>' + value.rank + '</td>';
movie_data += '<td>' + value.rating + '</td>';
movie_data += '<td>' + value['rating-count'] + '</td>';
movie_data += '<tr>';
});
$('#movie_table').slice(1).remove(); // To remove everything except first row
$('#movie_table').append(movie_data);
}
});
<!DOCTYPE html>
<html>
<head>
<title>JSON data to HTML table</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<div class="table-responsive">
<h1>TOP MOVIES</h1>
<button id="btn-sort">Sort</button>
<br />
<table class="table table-bordered table-striped" id="movie_table">
<tr>
<th>Title</th>
<th>IMDB-ID</th>
<th>RANK</th>
<th>RATING</th>
<th>RATING-COUNT</th>
</tr>
</table>
</div>
</div>
</body>
</html>

Related

Trying to remove the whole table row html javascript

JAVASCRIPT
function takeOut(el) {
el.parentElement.remove();
}
document.getElementById('myButton').onclick = function () {
const name = document.getElementById('name').value;
const date = document.getElementById('date').value;
const amount = document.getElementById('amount').value;
const nameTd = '<td>' + name + '</td>';
const dateTd = '<td>' + date + '</td>';
const amountTd = '<td>' + '$'+ amount + '</td>' + '<td>' +
'<button id="removeBtn"type="button" onClick="takeOut(this)">X</button></td>';
const tr = '<tr>' + nameTd + dateTd + amountTd + '</tr>';
document.getElementById('table').insertAdjacentHTML('beforeend', tr);
document.getElementById('clearList').onclick = function () {
const cl = document.getElementById('table');
while (cl.hasChildNodes()) {
cl.removeChild(cl.firstChild);
}
}
document.getElementById('name').value = '';
document.getElementById('amount').value = '';
document.getElementById('date').value = '';
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<h3>Add A New Item:</h3>
<label>Name: <input text="text" id="name"></label><br>
<label>Date:<input type="date" id="date"></label><br>
<label>Amount:<input text="text" id="amount"></label><br>
<button type="button" id="myButton">Add Expense</button>
<button type="button" id="clearList">Clear List</button>
<br>
<br>
<br>
<br>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Remove</th>
</tr>
<tbody id="table">
</tbody>
</table>
<script src="script2.js"></script>
</body>
</html>
Hey so im trying to make the button with the x remove the whole element that its in so after the user inputs the expense they can remove that certain one. Everytime I click the button it only removes the actual button not the whole input.
It actually removes the parent element that has the button. But that is a td element. You want to delete the grandparent, so do:
el.parentElement.parentElement.remove();
It may be easier to just look for the closest tr element (among the ancestor elements):
el.closest("tr").remove();
function takeOut(el) {
el.closest("tr").remove();
}
document.getElementById('myButton').onclick = function() {
const name = document.getElementById('name').value;
const date = document.getElementById('date').value;
const amount = document.getElementById('amount').value;
const nameTd = '<td>' + name + '</td>';
const dateTd = '<td>' + date + '</td>';
const amountTd = '<td>' + '$' + amount + '</td>' + '<td>' +
'<button id="removeBtn"type="button" onClick="takeOut(this)">X</button></td>';
const tr = '<tr>' + nameTd + dateTd + amountTd + '</tr>';
document.getElementById('table').insertAdjacentHTML('beforeend', tr);
document.getElementById('clearList').onclick = function() {
const cl = document.getElementById('table');
while (cl.hasChildNodes()) {
cl.removeChild(cl.firstChild);
}
}
document.getElementById('name').value = '';
document.getElementById('amount').value = '';
document.getElementById('date').value = '';
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<h3>Add A New Item:</h3>
<label>Name: <input text="text" id="name"></label><br>
<label>Date:<input type="date" id="date"></label><br>
<label>Amount:<input text="text" id="amount"></label><br>
<button type="button" id="myButton">Add Expense</button>
<button type="button" id="clearList">Clear List</button>
<br>
<br>
<br>
<br>
<br>
<table border="1">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Remove</th>
</tr>
<tbody id="table">
</tbody>
</table>
<script src="script2.js"></script>
</body>
</html>

When paging the table with JS, the data from the Firebase database does not appear

I am extracting data from Firebase database using Javascript. I list them with table. I need to paging because this data is quite a lot. I did not apply the paging method in the following link to my script and this paging works.
JS Pagination URL:
https://datatables.net/examples/styling/bootstrap
My problem is that the data comes from the database, so this script doesn't see my data and doesn't paging them and writes in index.html. "No data available in table"
This is because this paging function runs immediately when the script is first loaded.
Function:
$(document).ready(function() {
$('#userlist-table').DataTable();
} );
It also works great when I put the data loaded from the database into the "table" as HTML.
<tbody><tr id="++-LstSrLoH2UdYFvYJRn9" role="row" class="odd"><td class="sorting_1">John Doe</td><td>A</td><td>Melbourne</td></tr><tr id="++-LstSrLoH2UdYFvYJRnA" role="row" class="even"><td class="sorting_1">John Doe</td><td>A</td><td>Melbourne</td></tr><tr id="++-LstSrLoH2UdYFvYJRnB" role="row" class="odd"><td class="sorting_1">John Doe</td><td>A</td><td>Melbourne</td></tr><tr id="++-LstSrLoH2UdYFvYJRnC" role="row" class="even"><td class="sorting_1">John Doe</td><td>A</td><td>Melbourne</td></tr></tbody>
Somehow I have to run this function a little later and introduce the data in the table in the HTML to the paging function. I tried to use a timer, but I didn't get results and I wasn't able to generate an idea because I was new to JS. How can I solve this problem? I'm sorry about my bad English.
My HTML:
<head>
<!-- jquery latest version -->
<script src="assets/js/vendor/jquery-2.2.4.min.js"></script>
<!-- table pagination css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>
<script src="js/myscript.js"></script>
</head>
<body>
<table id="userlist-table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr id="tr">
<th>Name</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
</table>
</body>
My Script:
var database = firebase.database().ref('MyDatabase');
database.once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr id="' + "++" + data.key + '">';
content += '<td>' + val.name + '</td>';
content += '<td>' + val.position + '</td>';
content += '<td>' + val.office + '</td>';
content += '</tr>';
});
$('#userlist-table').append(content);
}
});
$(document).ready(function() {
$('#userlist-table').DataTable();
} );
Yeah. I finally found the problem. This is because the ready paging script I used needs " ". I added a hollow "tbody" to the ready set and filled it with data from the Firebase database. Then, when the script was loaded, I ran the paging function with the timer and everything seems to be running smoothly. It can solve the problem if someone needs it.
My HTML:
<head>
<!-- jquery latest version -->
<script src="assets/js/vendor/jquery-2.2.4.min.js"></script>
<!-- table pagination css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap.min.css">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap.min.js"></script>
<script src="js/myscript.js"></script>
</head>
<body>
<table id="userlist-table" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr id="tr">
<th>Name</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
<tbody></tbody>//add this element for pagination script
</table>
</body>
My Script:
var database = firebase.database().ref('MyDatabase');
window.setTimeout(getDatas, 2000);//add this line for timer with ur function for load datas
database.once('value', function(snapshot){
if(snapshot.exists()){
var content = '';
snapshot.forEach(function(data){
var val = data.val();
content +='<tr id="' + "++" + data.key + '">';
content += '<td>' + val.name + '</td>';
content += '<td>' + val.position + '</td>';
content += '<td>' + val.office + '</td>';
content += '</tr>';
});
$('#userlist-table').append(content);
}
});
function getDatas(){
$('#userlist-table').DataTable();
} //add this function, when loaded page, works it with timer

The search fails With AJAX call

The data search works fine for normal table data. When Iam filling the table body with Ajax call the search is not working.
I am using AJAX call to fill the table body. My table search works well If there is some Dummy Data without Ajax call. After the Ajax call the search is not working...
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>
</head>
<body>
<table id="myTable" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Salary</th>
</tr>
</thead>
<tbody id="userdetails1">
</tbody>
</table>
</body>
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables.css">
<link rel="stylesheet" type="text/css" href="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/css/jquery.dataTables_themeroller.css">
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://ajax.aspnetcdn.com/ajax/jquery.dataTables/1.9.0/jquery.dataTables.min.js"></script>
<script src="js/admin-dashboard.js"></script>
<script>
$(document).ready(function() {
$('#myTable').DataTable();
});
$('#myTable input').on('keyup', function() {
table.search(this.value).draw();
});
</script>
</body>
</html>
The issue is not with your ajax calls
rather it's with your data-table initializing
with reference to your codepen link:
https://codepen.io/jithendraathipatla/pen/JQMxvg?editors=1111
do this: in document.ready
$(document).ready(function() {
$('#myTable').DataTable();
function filterGlobal () {
$('#myTable').DataTable().search(
$('#global_filter').val(),
).draw();
}
function filterColumn ( i ) {
$('#myTable').DataTable().column( i ).search(
$('#col'+i+'_filter').val(),
).draw();
}
$('input.global_filter').on( 'keyup click', function () {
filterGlobal();
} );
$('input.column_filter').on( 'keyup click', function () {
filterColumn( $(this).parents('tr').attr('data-column') );
} );
} );
and in your js file replace your code with:
var waitlistTable=[];
waitlistdatashow();
function waitlistdatashow(){
console.log("hi");
var data = {"hosted_event_id": "testkonfhub-php-ban963c6ec2",
"user_id" : "1548232247"
};
// document.getElementById("userdetails").innerHTML = "<i class=\"fa fa-refresh fa-spin\" style=\"font-size:48px\"></i> ";
$.ajax({
url: "https://mr6akjmp7f.execute-api.us-east-2.amazonaws.com/default/konfhub_event_display_wailist_details",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
async:false,
success: function (data) {
console.log(data);
waitlistTable=data.participant_details;
console.log(waitlistTable);
//document.getElementById("event_name1").innerHTML = waitlistTable.event_name;
for(var i=0; i < waitlistTable.length; i++){
$("#userdetails1").append(
//"<th>Date & Time of Purchase</th>" +
"<tr>"+
"<td style='cursor: default'>" + waitlistTable[i].name + "</td>" +
"<td style='cursor: default'>" +
" <span class=\"block-email\" >" + waitlistTable[i].email_id.slice(0, 25) + "</span>" +
"</td>" +
"<td class=\"desc\">" + waitlistTable[i].phone_number + "</td>" +
"<td class=\"desc\">" + waitlistTable[i].organisation + "</td>" +
"<td class=\"desc\" id=\"waitlisttext\" style=\"color:orange\">" + waitlistTable[i].ticket_status + "</td>" +
// "<td><textarea id=" + "lead_text".concat(no_of_participant) + " rows=\"1\" cols=\"50\" type=\"text\" style=\"width:100%;border: 1px solid lightslategrey;padding: 4px;border-radius: 4px;\" placeholder=\"write comments here..\">" + returnLeadText(king[no_of_participant].misc) + "</textarea></td>" +
// "<td><span id=" + "approve".concat(no_of_participant) + " class='fas fa-check-circle click-check' onclick=\"approveWaitlist(" + no_of_participant + ")\" style=\"cursor:pointer;font-size: 25px;color:green\" data-toggle=\"tooltip\" title=\"Approve\">&nbsp&nbsp</span>"+
//"<div id=" + "delete-waitlist".concat(no_of_participant) + " class='far fa-times-circle click-check1' onclick=\"deleteWaitlistRecord(" + no_of_participant + ")\" style=\"cursor:pointer; font-size: 25px;color:red\" data-toggle=\"tooltip\" title=\"Reject\"></div></td>" +
"<\tr>"+
"<hr>"
);
// if(waitlistTable[i].status=="ACTIVE"){
// document.getElementById("refundbtn".concat(i)).style.display = "block";
// document.getElementById("cancelbtn".concat(i)).style.display = "block";
}
$('#myTable').DataTable();
}
});
}

ajax call goes to error function when i try to redirect from 1st jsp to 2nd jsp

I have created 2 jsp pages.In the 1st jsp screen there is a button called "display".when i click this button the page should redirect to the 2nd jsp screen.
I was able to redirect to the 2nd jsp page using window.location() in javascript but the ajax call fails and goes to the error function(). When i click the display button it does not show any dynamic data that is appended to the 2nd jsp.(shows only static content).`
//this is my javascript
var rowsperpage = 10;
var pageno = 1;
var totalpages = 0;
var tablecount=0;
function display()
{
var flag="two";
$.ajax({
type: "POST",
url: 'maunualmappingloadutility.jsp?value='+flag+'&Rowsperpage='+rowsperpage+'&Pageno='+pageno,
success: function(response)
{
var data = $.parseJSON(response);
var status = data.status;
if(status && status == "sucess")
{
var tbl="";
var textfilemapping=data.textfilemapping;
$.each(textfilemapping, function(key, value)
{
var id = value.id;
var data1 = value.col1;
var data2 = value.col2;
var data3 = value.col3;
var data4 = value.col4;
var data5 = value.col5;
var data6 = value.col6;
var data7 = value.col7;
var data8 = value.col8;
var data9 = value.col9;
tbl += '<tr id="'+id+'">';
tbl += '<td >' + id + '</td>';
tbl += '<td >' + data1 + '</td>';
tbl += '<td >' + data2 + '</td>';
tbl += '<td >' + data3 + '</td>';
tbl += '<td >' + data4 + '</td>';
tbl += '<td >' + data5 + '</td>';
tbl += '<td >' + data6 + '</td>';
tbl += '<td >' + data7 + '</td>';
tbl += '<td >' + data8 + '</td>';
tbl += '<td >' + data9 + '</td>';
tbl += '</tr>';
});
// window.location="display.jsp";
$("#textfiledata").html(tbl);
pageno = data.PAGENO;
totalpages = data.TOTALPAGES;
rowsperpage = data.ROWSPERPAGE;
enablePrevNext();
if(pageno == 1) {
$("#btnPrev").addClass("disabled");
} else if(pageno == totalpages) {
$("#btnNext").addClass("disabled");
}
$("#txtPage").val(pageno);
$('#lblTotalPages').html(totalpages);
}
else
{
alert("Error in displaying snomed info data");
return false;
}
},
error: function()
{
alert("Error in displaying snomed info data");
return false;
}
});
}
function Redirect() {
window.location="display.jsp";
display();
}
function om_nPageRefresh() {
location.reload();
}
//this is the 1st jsp with the display button in it
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui-1.8.17.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/encstyle.css" />
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.custom.min.js"></script>
<script type="text/javascript" src="js/textfileloadutility.js"></script>
</head>
<body>
<div class="blue-nav">
<div class="blue-pad">
<div class="dropdown referal-drop pull-left">
SNOMED CT Manual Mapping Load Utility
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="fileter-wrap">
<form class="form-horizontal" role="form">
<div style=text-align:center;margin:auto;>
<input class="btn btn-blue btn-sm btn-xs " id="clickMe" type="button" value="Load" onclick="check();" />
</div>
<div id="Message"></div>
</form>
<div class="clearfix spacer10"></div>
<div class="clearfix spacer10"></div>
</div>
<div class="fileter-wrap">
<label>Task status:</label>
<div style=text-align:center;margin:auto;>
<input style=text-align:center; id="click" type="submit" value="Display" onclick="Redirect();" />
</div>
</div>
</body>
</html>
//this is the 2nd jsp where the data is to be displayed
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery-ui-1.8.17.custom.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/jquery.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" media="screen" href="css/encstyle.css" />
<script type="text/javascript" src="js/jquery-1.11.0.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.custom.min.js"></script>
<script type="text/javascript" src="js/textfileloadutility.js"></script>
</head>
<body>
<div class="blue-nav">
<div class="blue-pad">
<div class="dropdown referal-drop pull-left">
SNOMED CT Manual Mapping Load Utility
</div>
<div class="clearfix"></div>
</div>
</div>
<div class="fileter-wrap">
<table class="table table-bordered grey-table nomargin" id="">
<thead>
<tr>
<th >ReferenceId</th>
<th >Id</th>
<th >Effective time</th>
<th >Active</th>
<th >Module id</th>
<th >Concept id</th>
<th >Language code</th>
<th >Type id</th>
<th >Term</th>
<th >CaseSignificanceid</th>
</tr>
</thead>
<tbody id="textfiledata">
</tbody>
</table>
<div class="clearfix spacer10"></div>
<div class="col-sm-15 cust-paged">
<div class="col-sm-5">
<button id="btnPrev" class="btn btn-lblue btn-xs" onclick="onClickPrev();">PREVIOUSPAGE</button>
<span>Page</span>
<input type="text" value="" class="search" id="txtPage" onkeydown="search(this)" >
<span>of <label id="lblTotalPages"></label></span>
<button id="btnNext" class="btn btn-lblue btn-xs" onclick="onClickNext();">NEXTPAGE</button>
</div>
</div>
<div class="clearfix spacer10"></div>
</div>
</body>
</html>
I have created 2 jsp pages.In the 1st jsp screen there is a button called "display".when i click this button the page should redirect to the 2nd jsp screen.
I was able to redirect to the 2nd jsp page using window.location() in javascript but the ajax call fails and goes to the error function(). When i click the display button it does not show any dynamic data that is appended to the 2nd jsp.(shows only static content).`
NOTE:if i create the display button in the 2nd jsp the data is getting displayed properly in the 2nd jsp itself.

getJSON script returning "undefined"

I have had a look around on here and a number of other sites for the correct way to create an HTML table from and external json link and have come up with the below.
I am trying to pull the username and number of votes and display them in the table, multiple rows are created, all populated with "undefined".
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link re="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered table-striped table-hover" id="ragnarok_table">
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
<script>
$(document).ready(function(){
$.getJSON("https://ark-servers.net/api/?object=servers&element=voters&key=[REMOVED]&month=current&format=json", function(data){
var ragnarok_data = '';
$.each(data, function(val){
ragnarok_data += '<tr>';
ragnarok_data += '<td>'+val.nickname+'</td>';
ragnarok_data += '<td>'+val.votes+'</td>';
ragnarok_data += '</tr>';
});
$('#ragnarok_table').append(ragnarok_data);
});
});
</script>
</body>
</html>
I can see that others have run into this issue too, however, this is my first time diving into Javascript; the other questions have completely different code and the answers dont seem to work here. Any help would be much appreciated, thanks.
Just use a .forEach on data.voters.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link re="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered table-striped table-hover" id="ragnarok_table">
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
<script>
$(document).ready(function() {
$.getJSON("https://ark-servers.net/api/?object=servers&element=voters&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=current&format=json", function(data) {
var ragnarok_data = '';
data.voters.forEach(function (val) {
ragnarok_data += '<tr>';
ragnarok_data += '<td>' + val.nickname + '</td>';
ragnarok_data += '<td>' + val.votes + '</td>';
ragnarok_data += '</tr>';
});
$('#ragnarok_table').append(ragnarok_data);
});
});
</script>
</body>
</html>
Or, if you are dead set on jQuery, modify your $.each to be on the array you want data from data.voters, and to properly get the value:
$.each(data.voters, function (ignore, val) {
The second argument is the value, the first argument is the index. See more here:
https://api.jquery.com/jQuery.each/
You can use .each as below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>TEST</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link re="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
<table class="table table-bordered table-striped table-hover" id="ragnarok_table">
<tr>
<th>Username</th>
<th>Votes</th>
</tr>
</table>
</div>
<script>
$(document).ready(function() {
$.getJSON("https://ark-servers.net/api/?object=servers&element=voters&key=R72Uo7jcAXCVBjx1eGtDm8itWlrU59GHnuy&month=current&format=json", function(data) {
var ragnarok_data = '';
/*data.voters.forEach(function (val) {
*/
$(jQuery.parseJSON(JSON.stringify(data.voters))).each(function() {
ragnarok_data += '<tr>';
ragnarok_data += '<td>' + this.nickname + '</td>';
ragnarok_data += '<td>' + this.votes + '</td>';
ragnarok_data += '</tr>';
});
$('#ragnarok_table').append(ragnarok_data);
});
});
</script>
</body>
</html>

Categories

Resources