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);
Related
Example output image
I have a JSON file which I populate from excel via a bit of vba code. It comes out in the format of:
[{"Name":"testing1","Data":"15"},{"Name":"testing2","Data":"1"},{"Name":"testing3","Data":"3"}]
I wish to take this data to an HTML webpage. I want to print it as a simple list.
I've printed from a json object using something like:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var people = response.people;
var output = '';
for (var i = 0; i < people.length; i++) {
//console.log(people[i].name);
output += '<li>' + "Name: " + people[i].name + " Age:" + people[i].age + '</li>';
}
document.getElementById('people').innerHTML = output;
}
};
xhttp.open("GET", "people.json", true);
xhttp.send();
I want to know how to change it to print from the string array without the object.
Hello there i wanted to request an api with ajax.
The api has plain json (what i thought)
now i set up an ajax request in javascript but i get an undefined error for the variables.I think i know the problem but I dont know an answer yet.
<script type="text/javascript">
document.getElementById("button").addEventListener('click', loadUsers);
// Load Github USers
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "dontKnowtheUrl", true);
xhr.onload = function()
{
if(this.status == 200){
var stats = JSON.parse(this.responseText)
var output = "";
for(var i in stats){
output +=
'<div class="user">' +
'<ul>' +
'<li>p_level: '+stats[i].p_level+'</li>'+
'<li>p_currentmmr: '+stats[i].p_currentmmr+'</li>' +
'</ul>' +
'</div>';
}
document.getElementById("users").innerHTML = output;
}
}
xhr.send();
}
This was the javascript part
the json file from the api looks like this
{"results":
[{"p_id":"test",
"p_name":"test",
"p_level":"test",
"p_platform":"test",
"p_user":"test",
"p_currentmmr":"test",
"p_currentrank":"test",
"kd":"test"},
{"p_id":"test",
"p_name":"test",
"p_level":"test",
"p_platform":"test",
"p_user":"test",
"p_currentmmr":"test",
"p_currentrank":"test",
"kd":"test"}],
"totalresults":2}
My Guess is that the json file isnt a normal array because it contains the "results": and "totalresults" property.
Does Anyone know how to fix it without getting into the json file?
You're going to want to loop through stats.results instead of just stats, see the following example:
function loadUsers(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "dontKnowtheUrl", true);
xhr.onload = function()
{
if(this.status == 200){
var stats = JSON.parse(this.responseText)
var output = "";
for(var i in stats.results){
var row = stats.results[i];
output +=
'<div class="user">' +
'<ul>' +
'<li>p_level: '+row.p_level+'</li>'+
'<li>p_currentmmr: '+row.p_currentmmr+'</li>' +
'</ul>' +
'</div>';
}
document.getElementById("users").innerHTML = output;
}
}
xhr.send();
}
I realise that this question has been asked a lot. Unfortunately, I haven't been able to work out how to properly implement any of the solutions.
So I have 3 files all in the same folder. 1 python script that creates the json file based on data scraped online.
Python script:
jsonFile = {"title": bookTitle, "author": author}
jsonArray.append(jsonFile)
with open(data.json, 'w) as file:
json.dump(jsonArray, file)
The JSON file ends up looking like this:
[{"name": "Foo", "author": "bar"},
{"name": "Bart", "author": "Simpson"},
{"name": "Homer", "author": "Simpson"}]
Now I'm trying to get that data into my index.html and to display it in various ways such as a table.
Index.html:
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="table-container">
<table id="table">
<tr>
<th>Name</th>
<th>Author</th>
</tr>
</table>
</div></div>
<script>
var data = $.getJSON(data.json);
var table = document.getElementById("table");
data.forEach(function(object) {
var tr = document.createElement("tr");
tr.innerHTML = "<td>" + object.title + "</td>" + "<td>" + object.author + "</td>"
table.appendChild(tr);
});
</script></body>
I appreciate any pointers someone might be able to give. Side question: do I need to use JQuery? Is there a better way?
Checking if you need jQuery is easy via http://youmightnotneedjquery.com/
Based on their recommendation your JS-code would look like this:
var request = new XMLHttpRequest();
request.open('GET', 'data.json', true);
request.onload = function () {
if (this.status >= 200 && this.status < 400) {
// Success!
var data = JSON.parse(this.response); //this is your JSON that is returned from your API (python)
var table = document.querySelector('#table');
for (var i = 0; i < data.length; i++) {
var tr = document.createElement('tr');
tr.innerHTML = '<td>' + object.title + '</td>' + '<td>' + object.author + '</td>'
table.appendChild(tr);
}
} else {
// ERROR!!
}
};
request.onerror = function () {
// There was a connection error of some sort
};
request.send();
I am trying to fetch the json data fetched from a web service. I've fetched data successfully but I want to show it in a table form only after a button click.
The following code shows the name of table rows when the page is load.It should only appear after a button click.
Code:
<html>
<head>
<script language="javascript" type="text/javascript">
var request = null;
function createRequest()
{
try {
request = new XMLHttpRequest();
}
catch (trymicrosoft)
{
try {
request = new ActiveXObject("MsXML2.XMLHTTP");
}
catch (othermicrosoft)
{
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (failed) {
request = null;
}
}
}
if (request == null)
alert("Error creating request object!");
}
function getMessage(lat,lon)
{
alert(lat);
createRequest();
;
var dis = document.getElementById("dt_id").value;
var url = "http://localhost:8080/testrestfullapi/webresources/drugController/getdata/"+dis;
alert(url);
request.open("GET", url, true);
request.onreadystatechange = handleResponse;
request.send(null);
}
function handleResponse()
{
if (request.readyState == 4){
alert("readystate=4");
var check=request.status;
alert(check);
alert(request.responseText);
if(check.toString()=="200")
alert("status ok");
var det = eval("(" + request.responseText + ")");
alert(det);
var data = "";
var i = 0;
for (var property in det) {
alert("Entered in for loop");
if (Object.prototype.hasOwnProperty.call(det, property)) {
data = data + "<tr>";
data = data + "<td class=\"sorting_1\">" + det[i].disease + "</td>";
data = data + "<td class=\" sorting_1\">" + det[i].drug + "</td>";
data = data + "<td class=\" sorting_1\">" + det[i].trade + "</td>";
i++;
}
}
document.getElementById("table_data").innerHTML = data;
}
}
</script>
</head>
<body>
<div style="text-align:left; margin:8px 5px auto;">
<label for="dt_id">Please enter disease </label>
<input type="Text" id="dt_id" maxlength="25" size="25"/>
<input type='button' onclick='getMessage()' value='SUBMIT'>
</div>
<table>
<thead>
<tr role="row">
<th>Disease</th>
<th>Drug</th>
<th>Trade</th>
</tr>
</thead>
<tbody id="table_data">
</tbody>
</table>
</body>
</html>
You forgot to hide the table initially. Hide the table by using this attribute style="display:none;" .. Then in button click you can show the table when you want...
<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