Not able to Json response from rest server - javascript

Im trying to parse a Json response from a rest server using JavaScript and display the data.
The rest server works fine its just that i cant parse the data. I have looked at dozens of examples and from my understanding the code looks fine.
This is my first attempt at learning Ajax and if i fix this i can continue with my project.
This is the response
{"id":"1","author":"Bill Burke","title":"RESTful Java with JAX-RS","year":"2009"}
This is the server
#Path("/books") // JAX-RS annotation
public class BookResource {
#GET // JAX-RS annotation
#Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON, MediaType.TEXT_XML })
#Path("/{bookId}")
public Book getBook(#PathParam("bookId") String id) {
return BookDao.instance.getBook(Integer.parseInt(id));
}
}
This is the client
<!DOCTYPE html>
<html>
<head>
<title>Form to create a new resource</title>
<script type="text/javascript">
function getHTTPObject() {
var xhr = false;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xhr = false;
}
}
}
return xhr;
}
function grabFile(file) {
var request = getHTTPObject();
if (request) {
request.onreadystatechange = function() {
parseJ(request);
};
request.open("GET", file, true);
request.send(null);
}
}
function parseJ(request) {
if (request.readyState == 4) {
if (request.status == 200 || request.status == 304) {
var obj = JSON.parse(request.responseText);
document.getElementById("details").innerHTML = obj.id + " " + obj.author + " "
+ obj.title + " " + obj.year;
}
}
}
</script>
</head>
<body>
<a
href="http://localhost:8080/Distributed_REST_booksServer/rest/books/1"
onclick="grabFile(this.href); return false;">Book 1</a>
<br>
<div id="details"></div>
</body>
</html>
html console error
html console error after modification

Your server is returning XML, try to force it as JSON and maybe add an accept header to the request from the client.

Related

How to parse json using ajax script in ESP32 app

I am working on a project using ESP32, I get some data from some sensors and send it to a webpage hosted in the same board.
I read some info on the web and understood that is "better" to send all data from several sensors using json method, so my function to get and send data is this:
void handle_leituras()
{
String results_json = "{ \"data\": " + Data +
"," + "\"hora\": " + Hora +
"," + "\"temp_amb1\": " + Tout + " }";
server.send(200, "application/json", results_json);
}
Testing above function in serial monitor I have this data:
{"data": Domingo, 12/4/2020,"hora": 20:53,"temp_amb1": 25.75}
I found a script that can get only one data and print it on that page, this is the script:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("DATA").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "leituras", true);
xhttp.send();
}
Its my index page code that shows data on webpage:
const char pag_inicial[] PROGMEM = R"=====(
<!DOCTYPE html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
<title>My 1st test</title></head>
<html>
<body>
<div id="pagina">
<h1>System XPTO</h1>
<div>
Data: <span id="DATA">ND</span><br>
Hora: <span id="HORA">ND</span><br>
Temperatura Ambiente: <span id="TEMPAMB1">ND</span>
</div>
<div id="botoes">
<button type="button" onclick="sendData(0)" style="width: 80px; height: 30px; margin: 30px;">ON</button>
<button type="button" onclick="sendData(1)" style="width: 80px; height: 30px; margin: 30px;">OFF</button><BR>
</div>
<script>
setInterval(function() {
// Call a function repetatively with 1 Second interval
getData();
}, 1000); //2000mSeconds update rate
//function to set on / off a LED on my board
function sendData(led) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LEDState").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "setLED?LEDstate="+led, true);
xhttp.send();
}
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
</script>
</div>
</body>
</html>
)=====";
My problem is...I don't know how to modify this script to get more sensors values from the described above function.
Anybody can save me please?
Thanks in advance ;)
The standard XMLHttpRequest only supports responseText and responseXML, it does not support responseJSON property. However, as long as your server is sending a valid serialised JSON string, the responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse(), and then you can access each JSON element with dot notation:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
This piece of code works for all browsers that supports XMLHttpRequest and JSON as long as the server is sending a valid JSON object.

I get the Error code 401 when I run this script, what can I do?

I am a newbie in programming.
I have a sensor that is connected to the app via bluethooth. The app sends the data to the cloud service. I got a link from the cloud service that contains the data in a json format. Now I want this data to be displayed on my Website, but its cross domain and whatever I do it says 401 (Unauthorized).
<html>
<head>
<title>Sensor</title>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<h1>Sensor</h1>
<button onclick="myFunctionPost()">Start</button>
<div id="result" style="color:red"></div>
<script>
function myFunctionPost() {
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
}; getJSON('https://thetablewheremydatais$format=json').then(function(data) {
alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
result.innerText = data.result; //display the result in an HTML element
}, function(status) { //error detection....
alert('Something went wrong.');
});
}
</script>
</body>
</html>
Have you tried this line of code before you call the server with xhr.send()
xhr.withCredentials = true;

Uncaught TypeError: request.open is not a function

Code:
// urlget.html
<!DOCTYPE html>
<html>
<head>
<title>AJAX GET-request example</title>
</head>
<body style='text-align:center'>
<h1>Loading Web page into DIV</h1>
<div id='info'>This sentense will be replaced</div>
<script>
nocache = "&nocache=" + Math.random() * 1000000
request = new ajaxRequest()
request.open("GET", "urlget.php?url= amazon.com/gp/aw " + nocache, true)
request.onreadystatechange = function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
if (this.responseText != null)
{
document.getElementById('info').innerHTML = this.responseText
}
else alert('AJAX error: Data not received')
}
else alert("AJAX error: " + this.statusText)
}
}
request.send(null)
function ajaxRequest()
{
try
{
request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch(e2)
{
try
{
request = new ActivateXObject("Microsoft.XMLHTTP")
}
catch(e3)
{
request = false
}
}
}
function ret(request){return request}
ret(request)
</script>
</body>
</html>
I get this error:
Uncaught TypeError: request.open is not a function
request = new ajaxRequest() is not how you instantiate an AJAX request with JQuery. As such, request doesn't become initialized to an XMLHttpRequest object and therefore it has no open method.
See this for JQuery AJAX.

How do I have the text and xml files open in a new window/tab?

Here is the code. I am fairly new to JavaScript and I'm learning more every day. This code is from an example from a textbook. Thank you for your responses. Another question I'd like to ask is how can I display the returned text in an unordered list? Would that be something to include in the html side of things or can it be done within the JavaScript file?
window.addEventListener("load",initAll,false);
var xhr = false;
function initAll() {
document.getElementById("makeTextRequest").addEventListener("click",getNewFile,false);
document.getElementById("makeXMLRequest").addEventListener("click",getNewFile,false);
}
function getNewFile(evt) {
makeRequest(this.href);
evt.preventDefault();
}
function makeRequest(url) {
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
}
}
}
if (xhr) {
xhr.addEventListener("readystatechange",showContents,false);
xhr.open("GET", url, true);
xhr.send(null);
}
else {
document.getElementById("updateArea").innerHTML = "Sorry, but I couldn't create an XMLHttpRequest";
}
}
function showContents() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
if (xhr.responseXML && xhr.responseXML.childNodes.length > 0) {
var outMsg = getText(xhr.responseXML.getElementsByTagName("choices")[0]);
}
else {
var outMsg = xhr.responseText;
}
}
else {
var outMsg = "There was a problem with the request " + xhr.status;
}
document.getElementById("updateArea").innerHTML = outMsg;
}
function getText(inVal) {
if (inVal.textContent) {
return inVal.textContent;
}
return inVal.text;
}
}
By the looks of it, you are making an AJAX request and are receiving XML.
In this case, I would:
Open up a new page with window.open()(returns a new Window object)
And then change the document.body.innerHTML of that new page to the XML you have
If you had a webpage that held the XML(maybe the server you are requesting to has one), you can just do:
window.open("page.xml");

How to resolve the conflict two ajax request at a same time

I have one nominal.jsp page,which includes header.jsp.Here i am using Ajax for the first time, for the request in header.jsp,then for the second time Ajax request is called to the nominal.jsp,i am facing the conflict issue in the Ajax request. Because of this issue,my preferred drop-down list is not displayed. Sometimes when response is entered in the JavaScript, the drop-downs are displayed and if the response are not entered in the JavaScript, the drop-downs are not displayed. Tried my level best to resolve the issue, but could not resolve it. Please help me guys
thank u,
My header.jsp code:
<script>
headerDisplay();
function headerDisplay()
{ var url ='<%=request.getContextPath()%>/summary?operation=header';
transactionRequest(url);
}
function transactionRequest(url)
{
if (window.XMLHttpRequest)
{
req = new XMLHttpRequest();
req.onreadystatechange = transactionResponse;
try
{
req.open("POST", url, true); //was get
}
catch(e)
{
alert("Problem Communicating with Server\n"+e);
}
req.send(null);
}
else if (window.ActiveXObject)
{
// IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req)
{
req.onreadystatechange = transactionResponse;
req.open("POST", url, true);
req.send();
}
}
}
function transactionResponse()
{
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{ var servletVal = req.responseText;
var myObject = eval('(' + servletVal + ')');
var userId = myObject.userId;
}}}......
</script>
And,this is my nono.jsp code:
<%#include file="/pages/common/header.jsp"%>
<script>
function displayNominal()
{
document.getElementById("ajaxLoading").style.display="block";
var url ='<%=request.getContextPath()%>'+'/nominalList';
postRequest(url);
}
function postRequest(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = nominalSelect;
try {
req.open("POST", url, true); //was get
} catch (e) {
alert("Problem Communicating with Server\n" + e);
}
req.send(null);
} else if (window.ActiveXObject) {
// IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = nominalSelect;
req.open("POST", url, true);
req.send();
}
}
}
function nominalSelect() {
if (req.readyState == 4) // Complete
{
if (req.status == 200) // OK response
{
var servletVal = req.responseText;
var myObject = eval('(' + servletVal + ')');
var userId = myObject.userId;
if (userId == null || userId == "") {
window.location = '/accounts1/?status=session';
}
}}..
</script>
<body class="bodystyle" onload="displayNominal()">
<% if("N".equals(roleDemoStatus))
{%>
<!-- /#demo Header -->
<div style="top: 0px; display: block;" id="header" class="fixed">
<div class="outer">
<h1 class="blog-title" style="text-align:center;margin-top:10px;"><span style="font-weight: normal; color:#777777; font-size: 30px;">accounts<font color="#5DA915">1</font>.co</span> Demo Only - <font color="red">Click Here</font> To Use For Free Forever</h1>
</div><!-- .outer -->
<div style="display: block;" class="shadow"></div>
</div>
<!-- /#Demo Header -->
<%} %>
</body>
Again thanks for advance.
Use a single callback and a try/catch block to enforce the request order:
function transactionResponse()
{
// Check whether this is the initial callback or a subsequent one
if (!!transactionResponse.state)
{
try
{
//POST data from the GET request
}
catch(e)
{
//Get data from the GET request
}
}
// Set state after the initial callback reference
else
{
transactionResponse.state = this;
}
}
References
Long Polling Experiment

Categories