Facing undefined error in json using javascript - javascript

I am using javascript ajax to fetch data from the JSON API server and want to show these data in an HTML table.
But I get an undefined error in HTML data. That is
Name id
undefined undefined
There is my code
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id="Name"></div></td>
<td><div id="Id"></div></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Id").innerHTML = jsonObj.id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
What should I do to resove this? Thanks in advance.

The problem is that you are trying to access an object, but the output of the API is actually an array. You can get the first object by doing jsonObj[0], as follows:
<html>
<body>
<table class = "src">
<tr><th>Name</th><th>id</th></tr>
<tr><td><div id = "Name"></div></td>
<td><div id = "Id"></div></td></tr>
</table>
</body>
</html>
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
var url = "https://jsonplaceholder.typicode.com/users";
xmlhttp.onreadystatechange = function(e) {
if (this.readyState == 4 && this.status == 200) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(this.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").textContent = jsonObj[0].name;
document.getElementById("Id").textContent = jsonObj[0].id;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
See this codesandbox where the code is working.
Edit: As T.J. Crowder has mentioned, it is better to use textContent rather than innerHTML to avoid unwanted HTML to be rendered (never trust user input!).

Related

Rapidapi Api request with XMLHttpRequest

this is my second post, I hope to be luckier than last time end get some reply. 🙂
I’m trying to make a Rapidapi api request working with javascript ”XMLHttpRequest”
I must say that the api works perfectly with ios siri shortcut.
this is the code provided from apirapit site on the "XMLHttpRequest" section:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");
xhr.send(data);
And this is my code:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
xhttp.send();
}
</script>
</body>
</html>
Just to testing I created a simply bank html page to have the JSON response beneath the button just after pressing it. The result is just the string “ciao” i set before the this.responseText. If I remove the apikey or modify it with a wrong value an JSON error message appear ( so like the case posted, as I intentionally removed it).
Otherwise as said noting but “ciao” string
Is there any syntax error? Is there a logical reason why it behave like this?
Thanks
Franco
Trying adding a data variable as null. That's what RapidAPI provides in their code snippet.
function loadDoc() {
const data = null
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", URL);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "my key here");
xhttp.send(data);
}

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

JSON data to HTML using AJAX

I am trying to input the value of the currency using the Value="AUD" as a starter. I am very new to JSON and AJAX. I cannot work out why there is an 404 error linked to JSON.parse and XMLHttpRequest, any advise of where I am going wrong would be much appreciated. Thanks in advance.
`enter code here`
<html lang="en">
<head>
</head>
<body>
<div id ="forex-info">
<p id="currencyList" class="currencyList" value ="AUD">Australia</p>
<p id="rateList" class="event"></p>
</div
<script type="text/javascript">
var tableContainer = document.getElementById("forex-info");
var ourRequest = new XMLHttpRequest();
var myData = "http://api.fixer.io/latest".rates;
ourRequest.open('GET', myData, true);
ourRequest.onload = function loading() {
var ourData = JSON.parse(ourRequest.responseText);
renderHTML(ourData);
function renderHTML(data) {
var output = "";
for (var key in data)
{
output += "<p>" + key + output + "</p>"
}
}
};
</script>
</body>
The main issue is how your calling the api "http://api.fixer.io/latest".rates
You call rest endpoints by there address params or with query params.
Please see example below calling your specified endpoint. That should get you started
var myData = 'https://api.fixer.io/latest'
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let res = JSON.parse(xhttp.responseText)
Object.keys(res.rates).forEach((e)=>{
console.log(`${e}: ${res.rates[e]}`)
//Add your stuff here
})
}
};
xhttp.open("GET", myData, true);
xhttp.send();

AJAX get JSON function not looping

Question: Why the function is not able to retrieve the json object?
I also noticed when debugging the code on my browser that the console does one pass through the code but never comes back! I thought the way this works is by having the function at the bottom of the html code looping back up until the the request status is changed.
I am starting to learn html javascripting. Following a tutorial I have the following code for html page that gets and parse JSON object:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function ajax_get_json(){
//crate our XMLHttpRequestobject
var hr = new XMLHttpRequest();
//var p1 = "p1";
//creat some variable we need to sned to our php file
hr.open("GET", "mylist.Json", true);
//set content type information for sending url encoded variables in the
//reqeust
console.log(5+6);
hr.setRequestHeader("Content-type", "application/json", true);
//Acess the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatchange = function(){
if (hr.readyState == 4 && hr.status == 200){
var data = JSON.parse(hr.responseText);
var results = document.getElementsById("results");
results.innerHTML=data.user;
// document.getElementById("results").innerHTML = return_data;
}
}
//send the data to php now and wait for the response to update the
//status div
hr.send();
results.innerHTML = "reqeusting...";
// document.getElementById("results").innerHTML="processing...";
}
</script>
</head>
<body>
<div id="results"></div>
<script type="text/javascript">ajax_get_json();</script>
</body>
</html>
Here is the json object code
{"user":"John", "age":22, "country":"United States" }
Both files are sitting in my ubuntu server that has LAMP enabled. Here is what the directory looks like:
Apparently the problem lies in declaring var results within hr.onreadystatechange function. Moving the declaration to the top fixed the code. Here is the working code:
<!DOCTYPE html>
<html>
<head>
<script>
function ajax_get_json(){
var results = document.getElementById("results");
//crate our XMLHttpRequestobject
var hr = new XMLHttpRequest();
//var p1 = "p1";
//creat some variable we need to sned to our php file
hr.open("GET", "mylist.json", true);
//set content type information for sending url encoded variables in the
//reqeust
//console.log(5+6);
//hr.setRequestHeader("Content-type", "application/json", true);
hr.setRequestHeader("Content-type", "application/json", true);
//Acess the onreadystatchange event for the XMLHttpRequest object
hr.onreadystatechange = function(){
if (hr.readyState == 4 && hr.status == 200){
var data = JSON.parse(hr.responseText);
results.innerHTML=data.user;
// document.getElementById("results").innerHTML = return_data;
}
}
//send the data to php now and wait for the response to update the
//status div
hr.send(null);
results.innerHTML = "reqeusting...";
// document.getElementById("results").innerHTML="processing...";
}
</script>
</head>
<body>
<div id="results"></div>
<script>ajax_get_json();</script>
</body>
</html>

Reading JSON into JavaScript using XMLHttpRequest

I have an external JSON file that I am trying to read into my ajax and parse through, but I'm missing something. I'm trying to read it into an XMLHttpRequest object. Any ideas on what I'm doing wrong. I get no results.
External file (mypeeps.json) contains:
[
{"name":"Frank","age":"23","image_url":"frank.gif"},
{"name":"Jim","age":"24","image_url":"frank.gif"},
{"name":"Tom","age":"21","image_url":"frank.gif"},
{"name":"Betty","age":"28","image_url":"frank.gif"},
]
My code is:
<script type="text/javascript">
function ajax_get_json() {
var p = new XMLHttpRequest();
p.open("GET", "mypeeps.json", true);
p.setRequestHeader("Content-type", "application/json");
p.onreadystatechange = function () {
alert("Im in...");
if (p.readyState == 4 && p.status == 200) {
alert("Let me know I've gotten this far");
var data = JSON.parse(p.responseText);
var results = document.getElementById("myDiv").innerHTML;
results.innerHTML = data.name;
} else {
document.getElementById("myDiv").innerHTML = "waiting...";
}
}
document.getElementById("myDiv").innerHTML = "processing...";
}
</script>
<div id="myDiv"></div>
<script type="text/javascript">
ajax_get_json();
</script>

Categories

Resources