Fetching data from API but no data are being displayed in html - html

I'm trying to fetch a specific set of data from an API as shown in the code below. Fetching only the football home teams' name and displaying it into a table.
I am getting no errors but no data is being shown in my table.
xhr.onreadystatechange = function()
{
if(this.readyState == 4 && this.status == 200)
{
//document.getElementById('text').innerHTML = this.responseText;
const obj = JSON.parse(this.responseText);
for (var i=0; i<obj.length; i++)
{
var row = $('<tr><td>' + obj.response[i].teams.home.name + '</td></tr>');
$('#myTable').append(row);
}
}
}
xhr.onerror = function()
{
console.log('Request Error');
}
xhr.send();
}
when doing console.log(obj)

you could do something like this
xhr.onreadystatechange = function()
{
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status == 200)
{
//document.getElementById('text').innerHTML = this.responseText;
const obj = JSON.parse(xhr.responseText);
for (var i=0; i<obj.response.length; i++)
{
var row = $('<tr><td>' + obj.response[i].teams.home.name + '</td></tr>');
$('#myTable').append(row);
}
}
}
xhr.onerror = function()
{
console.log('Request Error');
}
xhr.send();

Related

No output after trying loading data on the fly using Json and ajax

var pageCounter = 1;
var animalContainer = document.getElementById("animal-info");
var btn = document.getElementById("btn");
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'https://learnwebcode.github.io/json-example/animals-1.json');
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = ourRequest.responseText;
renderHTML(ourData);
} else {
console.log("We connected to the server, but it returned an error.");
}
};
ourRequest.onerror = function() {
console.log("Connection error");
};
ourRequest.send();
pageCounter++;
if (pageCounter > 3) {
btn.classList.add("hide-me");
}
});
function renderHTML(data) {
var htmlString = "";
for (i = 0; i < data.length; i++) {
htmlString += "<p>" + data[i].name + " is a " + data[i].species + "</p>";
}
animalContainer.insertAdjacentHTML('beforeend', htmlString);
}
I have checked every thing and i don't know what is wrong with the code... I am trying to load information on the fly using Json and ajax
You did not parse your data to JSON so what you have to do is parse your "ourData" to JSON.. Remove and add this line of to your code.
var ourData = JSON.parse(ourRequest.responseText);

Displaying different JSON text on interval

How is it possible here to display next JSON data on intervals(20s for example)?
Here is the code for getting JSON data
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var data= response.data;
var output = '';
for(var i = 0;i < data.length;i++){
output += ''+data[0].data1+''+data[0].data2+'<br/>';
}
document.getElementById('placeholder').innerHTML = output;
}
};
xhttp.open("GET", "url.json", true);
xhttp.send();

Displaying random JSON data

I have this code that displays JSON data. How could this code be remade to display random JSON data every 30 seconds?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var data= response.data;
var output = '';
for(var i = 0;i < data.length;i++){
output += ''+data[0].data1+''+data[0].data2+'<br/>';
}
document.getElementById('placeholder').innerHTML = output;
}
};
xhttp.open("GET", "url.json", true);
xhttp.send();
Here is an example of JSON
{
"data": [
{
"data":"John",
"data2": "Doe"
},
{
"data":"Nick",
"data2": "Doe"
},
]
}
How would it be best to use with setInterval, so that one minute "John Doe" is displayed, and other "Nick Doe"?
create a setInterval to call your logic every 30secs. Set index=0 initially and reset when it equals to your json's length.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var response = JSON.parse(xhttp.responseText);
var data= response.data;
var output = '';
var index = 0; // set your index
setInterval(function(){
if (index == data.length){
index= 0; // reset when equals json's length
}
output = ''+data[index].data1+''+data[index].data2+'<br/>';
document.getElementById('placeholder').innerHTML = output;
index++; // move to next element
},30000);
}
};
xhttp.open("GET", "url.json", true);
xhttp.send();

Uncaught SyntaxError: Unexpected token u in json

I have read online that the unexpected token issue can come from using JSON.parse().
I am getting this error Uncaught SyntaxError: Unexpected token u
What I am doing wrong?
My code look like this
var t=null;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function(responseText)
{
if (xmlhttp.readyState == 4 &&xmlhttp.status==200)
var obj = JSON.parse(xmlhttp.responseText);
var str=JSON.stringify(obj);
var newArr = JSON.parse(str);
var len=newArr.length;
$.mobile.pageContainer.pagecontainer( "change","sales_home.html");
$(document).on('pageshow', "#temp", function (event, data) {
while (len > 0) {
len--;
}
});
}
xmlhttp.onerror=function(E)
{
alert("error"+ E);
}
xmlhttp.open("GET","url",true);
xmlhttp.send();
The problem becomes apparent if you indent the code consistently and correctly:
var t = null;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(responseText) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
var obj = JSON.parse(xmlhttp.responseText);
var str = JSON.stringify(obj); // <====
var newArr = JSON.parse(str); // <====
var len = newArr.length;
$.mobile.pageContainer.pagecontainer("change", "sales_home.html");
$(document).on('pageshow', "#temp", function(event, data) {
while (len > 0) {
len--;
}
});
}
xmlhttp.onerror = function(E) {
alert("error" + E);
}
xmlhttp.open("GET", "url", true);
xmlhttp.send();
Note how the code does
var str = JSON.stringify(obj);
var newArr = JSON.parse(str);
no matter what the value of readyState and status are. That causes the error, because obj will be undefined, so JSON.stringify(obj) will return undefined, so JSON.parse will coerce that to the string "undefined", which it then cannot parse, failing on the first character, u.
You probably want to add a block:
var t = null;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(responseText) {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { // Block starts here
var obj = JSON.parse(xmlhttp.responseText);
var str = JSON.stringify(obj);
var newArr = JSON.parse(str);
var len = newArr.length;
$.mobile.pageContainer.pagecontainer("change", "sales_home.html");
$(document).on('pageshow', "#temp", function(event, data) {
while (len > 0) {
len--;
}
});
} // Block ends here
}
xmlhttp.onerror = function(E) {
alert("error" + E);
}
xmlhttp.open("GET", "url", true);
xmlhttp.send();
Not quite following why you're parsing, then stringifying, then parsing again though... Or why you have an empty while loop...

How to save a image to HTML5 filesystem with the url of image

I am trying to use HTML5 system to store images of my website, and I find there are many example to show how to store a local image to your chrome file system but I can't find the way to get a image by web url and then store it in HTML5 file system.
This is my code, but it's wrong.
lib.ajax.get(file , function(xhr, data){
if(xhr.status == 200){
fs.root.getFile("test.jpg", {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
// Create a new Blob and write it to log.txt.
var bb = new BlobBuilder(); // Note: window.WebKitBlobBuilder in Chrome 12.
bb.append(data);
fileWriter.write(bb.getBlob('image/jpeg'));
callback && callback("test.jpg");
}, errorHandler);
}, errorHandler);
}
});
The problem is that browser will parse xhr response data as UTF-8,
So the point is to override MimeType:
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
var xhr = new XMLHttpRequest();
var photoUrl = 'http://localhost:3000/image.jpg';
xhr.open('GET', photoUrl, true);
// This stops the browser from parsing the data as UTF-8:
xhr.overrideMimeType('text/plain; charset=x-user-defined');
function stringToBinary(response) {
var byteArray = new Uint8Array(response.length);
for (var i = 0; i < response.length; i++) {
byteArray[i] = response.charCodeAt(i) & 0xff;
}
return byteArray
}
function onInitFs(fs) {
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
fs.root.getFile('image.jpg', {'create': true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(event) {
$('body').append('<img src="' + fileEntry.toURL() + '"/>');
}
buffer = stringToBinary(xhr.response);
var blob = new Blob([ buffer ], { type: 'image/jpeg' } )
fileWriter.write(blob);
}, errorHandler );
});
}
}
xhr.send();
}
var errorHandler = function(err) {
console.log(err);
}
$(function() {
webkitStorageInfo.requestQuota(PERSISTENT, 5*1024*1024, function(grantedBytes) {
requestFileSystem(PERSISTENT, grantedBytes, onInitFs, errorHandler)
}, errorHandler)
})
Here the function I use.
It use Blob constructor so it works on latest Chrome (thats lacks deprecated BlobBuilder) and works also on old iOS 6 that lacks 'blob' for xhr.responseType.
In comments you also see code for the deprecated BlobBuilder.
Notice: you are using XHR so CORS must be enabled!
window.requestFileSystem = window.requestFileSystem || window.webkitRequestFileSystem;
window.requestFileSystem(window.PERSISTENT, 2*1024*1024, onFileSystemSuccess, fail);
function onFileSystemSuccess(fileSystem) {
fs = fileSystem;
console.log('File system initialized');
saveAsset('http://www.example-site-with-cors.com/test.png');
}
function saveAsset(url, callback, failCallback) {
var filename = url.substring(url.lastIndexOf('/')+1);
// Set callback when not defined
if (!callback) {
callback = function(cached_url) {
console.log('download ok: ' + cached_url);
};
}
if (!failCallback) {
failCallback = function() {
console.log('download failed');
};
}
// Set lookupTable if not defined
if (!window.lookupTable)
window.lookupTable = {};
// BlobBuilder shim
// var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder || window.MSBlobBuilder;
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
// xhr.responseType = 'blob';
xhr.responseType = 'arraybuffer';
xhr.addEventListener('load', function() {
fs.root.getFile(filename, {create: true, exclusive: false}, function(fileEntry) {
fileEntry.createWriter(function(writer) {
writer.onwrite = function(e) {
// Save this file in the path to URL lookup table.
lookupTable[filename] = fileEntry.toURL();
callback(fileEntry.toURL());
};
writer.onerror = failCallback;
// var bb = new BlobBuilder();
var blob = new Blob([xhr.response], {type: ''});
// bb.append(xhr.response);
writer.write(blob);
// writer.write(bb.getBlob());
}, failCallback);
}, failCallback);
});
xhr.addEventListener('error', failCallback);
xhr.send();
return filename;
}
function fail(evt) {
console.log(evt.target.error.code);
}
On a modern browser supporting XMLHttpRequest Level 2 the method documented in this answer should work.
The relevant standard is explained in this blog post
The trick is to use xhr.responseType = 'blob'
var fs = .... // your fileSystem
function download(fs,url,file,win,fail) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = "blob";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if(xhr.status === 200){
fs.root.getFile(file,{create:true},function(fileEntry){
fileEntry.createWriter(function(writer){
writer.onwriteend = win;
writer.onerror = fail;
writer.write(xhr.response);
})
},fail)
} else {
fail(xhr.status);
}
}
};
xhr.send();
return xhr;
};
Based on cordova-promise-fs (disclosure: I'm the author)
I find a way to do this.
use canvans.toDataURL to transfer data format.
var img = new Image();
var cvs = document.createElement('canvas');
var ctx = cvs.getContext("2d");
img.src = file;
img.onload = function(){
cvs.width = img.width;
cvs.height = img.height;
ctx.drawImage(img, 0, 0);
var imd = cvs.toDataURL(contentType[extname]);
var ui8a = convertDataURIToBinary(imd);
var bb = new BlobBuilder();
bb.append(ui8a.buffer);
fs.root.getFile(path, {create: true}, function(fileEntry) {
// Create a FileWriter object for our FileEntry (log.txt).
fileEntry.createWriter(function(fileWriter) {
fileWriter.onwriteend = function(e) {
console.log('Write completed.');
callback && callback("test.jpg");
};
fileWriter.onerror = function(e) {
console.log('Write failed: ' + e.toString());
};
fileWriter.write(bb.getBlob(contentType[extname]));
});
});
};
function convertDataURIToBinary(dataURI) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var array = new Uint8Array(new ArrayBuffer(rawLength));
for (i = 0; i < rawLength; i++) {
array[i] = raw.charCodeAt(i);
}
return array;
}
I get help from here jsfiddle