I am new to web development, and I am using a XMLHttpRequest() in JavaScript to get data from an api. I am trying to create variables from the data but am getting an error when I try to do the following. Does anyone know what is wrong with the line var data1 = data["data1"];?
<script>
const Http = new XMLHttpRequest();
const url = "www.mytestapi.com/response.json";
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
var json = JSON.parse(Http.responseText)
var data = json.Data
var data1 = data["data1"]; //issue caused here
}
<script>
you don't need to parse response data, data is parsed already , try this
const xhr = new XMLHttpRequest();
const url = "www.mytestapi.com/response.json";
xhr.open('GET', url);
xhr.responseType = 'json';
xhr.onload = () => {
console.log("load - "+ JSON.stringify(xhr.response));
var data = xhr.response;
var data1 = data["data1"]
}
xhr.onerror = () => {
console.log("error status - " + xhr.status);
}
xhr.send()
Related
I'm trying to connect by hand to Colyseus. I am trying now with node but I don't understand why I can't get past the first message.
Here is the code:
var WebSocket = require('ws');
var XMLHttpRequest = require('xhr2');
var xhr = new XMLHttpRequest()
var myurl = "http://localhost:2567/matchmake/joinOrCreate/my_room"
var res = '';
var socket = '';
let data = `{ "Id": 123}`;
xhr.open("POST", myurl);
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
res = JSON.parse(xhr.responseText);
var processId = res['room']['processId'];
var roomId = res['room']['roomId'];
var sessionId = res['sessionId'];
var wsurl = "ws://localhost:2567/"+processId+"/"+roomId+"?sessionId="+sessionId;
socket = new WebSocket(wsurl);
socket.onmessage = (event) => {
console.log('Message from server ', event.data);
};
}
};
xhr.send(data);
I can see the first message, but when I "broadcast" a message by changing something on the server state, nothing appears. If I connect with the official library, I do see messages going back and forth.
Am I missing something?
enter image description hereThe problem is that the objects of the API are not being rendered in HTML, what did I do wrong?
<button onclick = "showCountries()">Show Countries</button>
<div id = "feed"></div>
<script>
function showCountries(){
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function(){
if(xhr.status == 200){
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country=>{
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('img')
countryCard.innerHTML = country.name
countryCardImage.src = country.flag
document.getElementById('feed').appendChild(countryCard)
})
}
}
xhr.send()
}
</script>
Because country.name is an object.You should use an string to set the innerHTML of element.
According to your response data structure, you can use it like this:
function showCountries() {
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function() {
if (xhr.status == 200) {
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country => {
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('img')
countryCard.innerHTML = country.name.common
countryCardImage.src = country.flags.png
countryCardImage.style.width = "30px"
countryCard.append(countryCardImage)
document.getElementById('feed').appendChild(countryCard)
})
}
}
xhr.send()
}
<button onclick="showCountries()">Show Countries</button>
<div id="feed"></div>
I finally figured out how to display flags, here is the source:
function showCountries(){
let xhr = new XMLHttpRequest()
xhr.open('GET', 'https://restcountries.com/v3.1/all', true)
xhr.onload = function(){
if(xhr.status == 200){
console.log('success')
let countries = JSON.parse(this.response)
countries.forEach(country=>{
const countryCard = document.createElement('div')
const countryCardImage = document.createElement('div')// must be div to display small image
countryCard.innerHTML = country.name.common
countryCardImage.innerHTML = country.flag
console.log(country.flag)
document.getElementById('feed').appendChild(countryCard)
document.getElementById('feed').appendChild(countryCardImage) //this is it!
})
}
}
This is returned by the REST API: [[5671, 204], [5673, 192], [5674, 120], [5683, 120], [5684, 192], [5685, 204]]
when i am doing typeof i am getting string for above in javascript . i want to convert it to a multi dimensional array.
<script type="text/javascript">
const Http = new XMLHttpRequest();
const url='/hello/get_pw_status';
Http.open("GET", url);
Http.send();
var resp;
Http.onreadystatechange = (e) => {
console.log(Http.responseText);
document.getElementById("demo").innerHTML =Http.responseText;
console.log(typeof Http.responseText);
var pw_data = [];
pw_data=Http.data;
console.log(pw_data);
}
Use JSON.parse to convert the array in the response string.
<script type="text/javascript">
const Http = new XMLHttpRequest();
const url='/hello/get_pw_status';
Http.open("GET", url);
Http.send();
var resp;
Http.onreadystatechange = (e) => {
var multiDimentionalArray;
if(typeof Http.responseText == "string") {
multiDimentionalArray = JSON.parse(Http.responseText);
}
conosle.log(multiDimentionalArray);
}
I use XMLHttpRequest to send POST data to nodejs (expressjs api). The size of file about 200mb. When I do, Chrome crashes, but the Firefox doesn't. Does Chrome have a limited file size?
And how can I upload the large file via JavaScript?
This is my code send xhr request:
// create http request API AI Engine
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.responseType = 'arraybuffer';
xhr.timeout = 3600000;
xhr.onload = function() {
// reponse measage
if (this.status === 200) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'none';
zip.files = {};
// unzip File
zip.loadAsync(this.response)
.then(function(zip) {
// will be called, even if content is corrupted
for (const file in zip.files) {
if (zip.files.hasOwnProperty(file)) {
const fileObject = zip.files[file];
fileObject.async('arraybuffer').then(function(fileData) {
var fileSave = new Blob([new Uint8Array(
fileData)]);
// Save file
saveAs(fileSave, fileObject.name);
})
}
}
}, function(e) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not unzip file return.';
});
// get response stream data
} else {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
}
};
// Handle when have error with xhr, show message
xhr.onerror = function(err) {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: ' + this.statusText;
};
// Handle when have timeout with xhr, show message
xhr.ontimeout = function() {
var errorArea = document.getElementById('error-area');
errorArea.style.display = 'block';
errorArea.innerHTML =
'<strong>Error</strong> Cant not analyze file: Request time out';
};
// Add custom header
xhr.setRequestHeader('Content-type', 'application/octet-stream');
xhr.setRequestHeader('file-name', Date.now().toString() + '.zip');
xhr.setRequestHeader('file-length', data.byteLength);
// Send arraybuffer to server
xhr.send(data);
});
I'm trying to convert the Blob data I receive to an array as follows:
var xhr = new XMLHttpRequest();
xhr.open('GET', "chrome://favicon/http://www.cnn.com/", true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
var favicon = new Uint8Array(this.response);
}
};
xhr.send();
But the line:
new Uint8Array(this.response);
doesn't result in an array. What's wrong here?
Figured it out:
var xhr = new XMLHttpRequest();
xhr.open('GET', "chrome://favicon/http://www.cnn.com/", true);
xhr.responseType = 'blob';
xhr.onload = function (e) {
if (this.status == 200) {
// get binary data as a response
//var blob = this.response;
//var favicon = new Uint8Array(this.response);
var reader = new FileReader();
reader.onload = function (e) {
mDataToTransmit.favicon = e.target.result;
transmitData();
};
reader.readAsDataURL(this.response);
}
};
xhr.send();