How to repeat parsing json data using javascript in html - javascript

I have this code from w3school works like a charm:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
but when I repeat the script like this it doesn't work:
<!DOCTYPE html>
<html>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
</script>
<h1>Buyers</h1>
<div id="id02"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://www.w3schools.com/website/customers_mysql.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
</script>
</body>
</html>
What variable name should I change? I did the script once it worked but twice it didn't work.
I tried changing variable but it didn't work
I changed all the variable names.

Your two scripts exist in the same JS environment. They both create global variables with the same name and interfere with each other.
Wrap each script in an IIFE to create a new scope for each one to operate in.
<script>
(function () {
// Your code here
})();
</script>

It doesn't work because you're executing AJAX call across domains. You can't do an ajax call like that unless you are calling a page on the same domain. There are workarounds, but this is the problem in your case.
Instead create a local file to test your AJAX with.
This is why it works on the w3 Schools site, but not on your own code.

Related

Why did I get undefined values when trying to read xml file?

I am trying to read data from a xml file and display them in my html file, but when I am trying to display my values I get "undefined" values for all the values.
I am a really new with ajax and xml so excuse my code if its horrible! I will appreciate if someone got a really briefly answer.
Here's my xml file:
<gesmes:Envelope xmlns:gesmes="http://www.gesmes.org/xml/2002-08-01" xmlns="http://www.ecb.int/vocabulary/2002-08-01/eurofxref">
<gesmes:subject>Reference rates</gesmes:subject>
<gesmes:Sender>
<gesmes:name>European Central Bank</gesmes:name>
</gesmes:Sender>
<Cube>
<Cube time="2019-01-25">
<Cube currency="USD" rate="1.1346"/>
<Cube currency="JPY" rate="124.72"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="25.697"/>
<Cube currency="DKK" rate="7.4664"/>
<Cube currency="GBP" rate="0.86580"/>
....
My javascript code:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
returndata(this);
}
};
xhttp.open("GET", "rates.xml", true);
xhttp.send();
}
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("currency")[0] +
"</td><td>" +
x[i].getElementsByTagName("rate")[0] +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
When I click the button I got the following result:
currency rates
undefined undefined
undefined undefined
undefined undefined
undefined undefined
.....
UPDATE Javascript code(fixed):
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 2; i <x.length; i++) {
table += "<tr><td>" +
x[i].getAttribute("currency") +
"</td><td>" +
x[i].getAttribute("rate") +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
Okay now it works, thank you very much, i started my variable from the value 2 because when i am trying to have a while loop like (x!=null) my webpage it still loading forever and then breaks down..
i tried that one:
function returndata(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>currency</th><th>rates</th></tr>";
var x = xmlDoc.getElementsByTagName("Cube");
for (i = 0; i <x.length; i++) {
while (x!=null) {
table += "<tr><td>" +
x[i].getAttribute("currency") +
"</td><td>" +
x[i].getAttribute("rate") +
"</td></tr>";
}
}
document.getElementById("demo").innerHTML = table;
}

Get json data based on url

I have a problem with getting the specific data based on my id.
This is my main html.
<div class="container">
<div class="row">
<div class="col-md-12">
<button id="btn">Button</button>
<br>
<div id="id01"></div>
</div>
</div>
</div>
This is my main js
var btn=document.getElementById("btn");
btn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
var url = "url.../incident";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
});
function myFunction(response) {
var arr = JSON.parse(response);
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Address +
"</td><td><a href='lista.html?id="+arr[i].ID+"'>" +
arr[i].ID +
"</a></td><td>" +
arr[i].Category +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
This will show me only three data.
this is my lista.html
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="id02">
</div>
</div>
</div>
And this is my js for my lista.html.
var ourRequest = new XMLHttpRequest();
var url = "url../incident?id=";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function()
{
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
function myFunction(response)
{
var arr = JSON.parse(response);
var out = "<table>";
out +="<tr><td>" +
arr.Address +
"</td><td>" +
arr.CaseID +
"</td><td>" +
arr.Category +
"</td><td>" +
arr.Date +
"</td><td>" +
arr.Description +
"</td><td>" +
arr.ID +
"</td><td>" +
arr.InputDate +
"</td><td>" +
arr.Latitude +
"</td><td>" +
arr.Longitude +
"</td><td>" +
arr.ReportedBy +
"</td><td>" +
arr.Subcategory +
"</td><td>" +
arr.Time +
"</td></tr>"
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
So when I click on that arr[i].ID it should send me to th lista.html with the specific ID and specific data.
For example if i click on ID=1, the url look like lista.html?id=1, but nothing shows.
Just pass the id to the request url if the api you send request to expects that
var url = "url?id={your id here}"
In your table you have to use arr.Address instead of response.Address, since the arr is the parsed json object.
You can use console.log to see if the data you need is really there:
function myFunction(response) {
var arr = JSON.parse(response);
console.log(arr);
}
You don't need to read the location href with jQuery, since you already know the id of the request you sent!
So My mistake was like this instead of :
var url = "url../incident?id=";
I should have written :
var url = "url../incident?id="+getQueryVariable("id");
And write this function in the end of my js for my lista.html
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}

Images aren't displaying from XML to HTML table

I am trying to get an image to display in the table below, the image isn't displaying instead just the URL to the image is. Below is the what I have put into the HTML file. I have copied it off another site and also do not want the push button option and I am not sure how to get rid of that.
<div id="container">
<table id="demo"></table>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>
<br><br>
<script>
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp);
}
};
xmlhttp.open("GET", "amateur.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var img = document.createElement("img");
var table="<tr><th>Rating</th><th>Title</th><th>Thumbnail</tr>";
var x = xmlDoc.getElementsByTagName("video");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("rating")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td>" +
img.src = x[i].getElementsByTagName("thumbnail")[0].childNodes[0].nodeValue
document.write(img.src);
document.body.appendChild(img)"</td></tr>";;
}
document.getElementById("demo").innerHTML = table;
}
</script>
</div>
This is a sample of what the XML file looks like, it has been edited slightly as it is inappropriate for the content to be shown. The XML file is called "amateur.xml"
<?xml version="1.0" encoding="utf-8"?>
<videos>
<video id="1fb853907b9ca6add9ac">
<url>a.com</url>
<categories>A</categories>
<rating>100</rating>
<title>A</title>
<tags>A;a;AB</tags>
<duration>15</duration>
<thumbnail>http://i1.cdn2a.image.phncdn.com/m=eGcE8daaaa/videos/201011/03/148553/original/12.jpg</thumbnail>
</video>
<video id="d95ebc6a75c00d9926e7">
<url>http://ab.com</url>
<categories>A;B;An</categories>
<rating>100</rating>
<title>Sie spritzt ab</title>
<tags>a;b;as;d</tags>
<duration>65</duration>
<thumbnail>http://i0.cdn2a.image..phncdn.com/m=eGcE8daaaa/videos/201102/17/160998/original/12.jpg</thumbnail>
</video>
</videos>
Why is there a document.write(img.src)? Normally, you use that when you put it in into an <img> tag but then you don't need to create the image object, like:
for (i = 0; i <x.length; i++) {
var img = x[i].getElementsByTagName("thumbnail")[0].childNodes[0].nodeValue;
table += "<tr><td>" +
x[i].getElementsByTagName("rating")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td><td><img src='"+img+"'></td></tr>";
}

How to read JSON data from a web server running PHP and MySQL?

I read example in http://www.w3schools.com/json/json_example.asp.
And I try it with my MySQL database and my PHP code. But it does not work.
I am a beginner and I don't know what it wrong.
Here is my PHP link: http://xebus2014.tk/demo.php
And I change w3school code like this:
<!DOCTYPE html>
<html>
<head>
<style>
h1 {
border-bottom: 3px solid #cc9900;
color: #996600;
font-size: 30px;
}
table, th , td {
border: 1px solid grey;
border-collapse: collapse;
padding: 5px;
}
table tr:nth-child(odd) {
background-color: #f1f1f1;
}
table tr:nth-child(even) {
background-color: #ffffff;
}
</style>
</head>
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "http://xebus2014.tk/demo.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].STT +
"</td><td>" +
arr[i].ID +
"</td><td>" +
arr[i].Name +
"</td><td>" +
arr[i].Singer +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>
</html>
Did you set the response as Json String?
header("Content-Type: application/json; charset=UTF-8");
Your result is already an object, so you don't need to parse it using JSON.parse, just use it as is and pass it through the loop as is.
I don't know about the cross domain issue, but to run it, I go directly to your function... see this fiddle for a working loop using your output -- http://jsfiddle.net/fu3g5Loe/
OR you may use this in your PHP backend
echo json_encode('Your result set goes here'); // this will apply the correct JSON representation of your result set before echoing
Working Code
<body>
<h1>Customers</h1>
<div id="id01"></div>
<script>
/*
var xmlhttp = new XMLHttpRequest();
var url = "http://xebus2014.tk/demo.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
*/
var params = [{"STT":"1","ID":"123","Name":"Sexy Love","Singer":"T-ara"},{"STT":"2","ID":"456","Name":"Day By Day","Singer":"T-ara"},{"STT":"3","ID":"789","Name":"Cry Cry","Singer":"T-ara"}];
myFunction(params);
function myFunction(response) {
var arr = response;
var i;
var out = "<table>";
for(i = 0; i < response.length; i++) {
out += "<tr><td>" +
arr[i].STT +
"</td><td>" +
arr[i].ID +
"</td><td>" +
arr[i].Name +
"</td><td>" +
arr[i].Singer +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
</body>

How to Retrive The Particular Book Details From Google My Library Through ID

<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

Categories