javascript cannot access array items - javascript

I have a global var: var url_device = [];
And a function that populate it.
request.onload = function () { //function pour les devices
// Begin accessing JSON data here
var valu = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
for (var i = 0; i < valu.data.length; i++) {
var namespace = valu.data[i].namespace;
var idd = valu.data[i].id;
url_device.push(url_data + namespace + idd);
}
for (var j = 0; j < 2; j++) {
request_data.open('GET', url_device[j], true);
request_data.setRequestHeader('Accept', 'application/json')
request_data.setRequestHeader('Content-type', 'application/json')
request_data.setRequestHeader('X-API-KEY', 'XXXXXXXXXXXXXXXX')
request_data.send();
request_data.onload = function () { //function pour les data des devices
var valu_d = JSON.parse(this.response);
}
}
}
}
Normally, url_device contains 2 items after my first request:
[] ​ 0: "https://url/api/v0/data/streams/apple1841" ​
1: "https://url/api/v0/data/streams/device19999" ​
length: 2 ​
__proto__: Array []
But I cannot access these items. That's why my second request, in the j loop doesn't work. I would like to GET data from the first url (item[0]), and the second one.

Related

Uncaught (in promise) TypeError: Cannot read property '0' of undefined

const promise = new Promise((resolve,rejest) =>{
const xhr = new XMLHttpRequest();
xhr.onload = () =>{
if(xhr.status >= 200 && xhr.status < 300){
resolve(xhr.response);
}else{
reject(xhr.statusText);
}
}
xhr.open("GET","../fetch.php?s="+option, true);
xhr.send();
}).then((result) =>{
const obj = JSON.parse(result);
let keys = Object.keys(obj[0]);
keys = Array.from(keys);
for(let i = 0; i < obj.length; i++){
for(let j = 0; j < keys.length; j++){
console.log(obj[i].keys[j]);
}
}
});
obj[i].keys[j]; returns undefined for some reason.
The JSON file looks like this:
[{"user_id":"3","user_name":"admin","user_password":"password","user_role":"admin"},{"user_id":"4","user_name":"some_user","user_password":"some_passowrd","user_role":"user"}]
When I try obj[0].user_name for example it returns the value.
I have to do that this way because I don't know the keys before loading it.

(beginner javascript) get multiple text files xml request

Very grateful if someone can help me out with the syntax here- I am hoping to make several XML requests, each time getting a different text file. Here is the general structure of my code. How can I get each file in turn (f0, f1 and f2)?
window.onload = function(){
var f = (function(){
var xhr = [];
for (i = 0; i < 3; i++){
(function (i){
xhr[i] = new XMLHttpRequest();
f0 = "0.txt"
f1 = "1.txt"
f2 = "2.txt"
//??? xhr[i].open("GET", file i, true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
//do stuff
}
};
xhr[i].send();
})(i);
}
})();
};
Simply put your filenames in an array.
window.onload = function(){
var f = (function(){
var xhr = [];
var files = ["f0.txt", "f1.txt", "f2.txt"];
for (i = 0; i < 3; i++){
(function (i){
xhr[i] = new XMLHttpRequest();
xhr[i].open("GET", files[i], true);
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
//do stuff
}
};
xhr[i].send();
})(i);
}
})();
};
Something like this should work
// ...
for (i = 0; i < 3; i++){
(function (i){
xhr[i] = new XMLHttpRequest();
xhr[i].open('GET', i.toString() + '.txt'); // <-- this line
xhr[i].onreadystatechange = function () {
if (xhr[i].readyState == 4 && xhr[i].status == 200) {
// ....

Chrome Extension: Data is not being inserted nor fetched

I am using WebSQL. I am trying to add data in Async Block which is making data not to be inserted. Code is given below:
function fetchData(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost/x/fetch.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
// JSON.parse does not evaluate the attacker's scripts.
var resp = xhr.responseText;
if(resp != null) {
var json = JSON.parse(resp)
console.log(resp);
var data = json['data'];
if(data != null) {
openDatabase('documents', '1.0', 'documents', 5*1024*1024, function (db) {
alert('Called'); // This is called after below two calls.
insertRecord(db);
fetchRecord(db);
});
//var dbConnection = openDbConnect();
//createTable(dbConnection);
for(var a=0;a <= data.length;a++) {
alert(data[a].title);
}
}
}
}
}
xhr.send();
}
JSON Dump
{"data":[{"id":"1","title":"- Parts I & II”,”CODE”:”xxx”,”product_url":"http:\/\/www.example.com","image_url":"http:\/\/ecx.images-example.com\/images\/I\/61ujIIMyW7L.jpg","price":"$25.00"},{"id":"2","title”:”AJDJDDJDr”,”Code”:”XX”,”product_url":"http:\/\/www.example.com","image_url":"http:\/\/dc.images-example.com\/images\/I\/41jFVZL72YL.jpg","price":"$10.99"}]}
Try this ;)
Problem in this loop condition:
for(var a = 0; a <= data.length; a++) {
^
Here you are starting from 0 and looping to data.length
So to loop with arrays as array index starts from 0 loop till a <= data.length - 1 OR a < data.length
for(var a = 0; a < data.length; a++) {
OR
for(var a=0; a <= (data.length - 1); a++) {
Instead of for loop you can use for...in like this:
for(var index in data){
alert(data[index].title);
}

Asynchronous execution of javascript code

I am studying javascript and json but I've some problems: I have a script that works with json but the performances of what I wrote aren't that good. The code works only if I do a debug step by step with firebug or other tools and that makes me think that the execution of the code (or a part of it ... the one that creates the table as you'll see) requires too much time so the browser stops it.
The code is:
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function() {
if(richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
for(i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function() {
if(richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for(j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for(u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for(c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
The problem is that the code that should make the table doesn't wait for the complete execution of the code that works with the json files. How can I fix it? I would prefer,if possible, to solve that problem with something easy, without jquery and callbacks (I am a beginner).
You'll have to move som code around to make that work. at first, split it up in some functions, then it is easier to work with. I dont know if it works, but the idea is that first it loads the arrayEntita. When that is done, it fills the other 2 arrays. And when the last array has been filled, it builds the table.
var arrayCarte = [];
var arrayEntita = [];
var arraycardbyuser = [];
function displayArrayCards() {
var richiestaEntity = new XMLHttpRequest();
richiestaEntity.onreadystatechange = function () {
if (richiestaEntity.readyState == 4) {
var objectentityjson = {};
objectentityjson = JSON.parse(richiestaEntity.responseText);
arrayEntita = objectentityjson.cards;
BuildArrayEntita();
}
}
richiestaEntity.open("GET", "danielericerca.json", true);
richiestaEntity.send(null);
}
function BuildArrayEntita() {
for (i = 0; i < arrayEntita.length; i++) {
var vanityurla = arrayEntita[i].vanity_urls[0] + ".json";
var urlrichiesta = "http://m.airpim.com/public/vurl/";
var richiestaCards = new XMLHttpRequest();
richiestaCards.onreadystatechange = function () {
if (richiestaCards.readyState == 4) {
var objectcardjson = {};
objectcardjson = JSON.parse(richiestaCards.responseText);
for (j = 0; j < objectcardjson.cards.length; j++)
arrayCarte[j] = objectcardjson.cards[j].__guid__; //vettore che contiene i guid delle card
arraycardbyuser[i] = arrayCarte;
arrayCarte = [];
//If it is the last call to populate arraycardbyuser, build the table:
if (i + 1 == arrayEntita.length)
BuildTable();
}
}
richiestaCards.open("GET", vanityurla, true);
richiestaCards.send(null);
}
}
function BuildTable() {
var wrapper = document.getElementById('contenitoro');
wrapper.innerHTML = "";
var userTable = document.createElement('table');
for (u = 0; u < arrayEntita.length; u++) {
var userTr = document.createElement('tr');
var userTdcard = document.createElement('td');
var userTdinfo = document.createElement('td');
var br = document.createElement('br');
for (c = 0; c < arraycardbyuser[u].length; c++) {
var cardImg = document.createElement('img');
cardImg.src = "http://www.airpim.com/png/public/card/" + arraycardbyuser[u][c] + "?width=292";
cardImg.id = "immaginecard";
userTdcard.appendChild(br);
userTdcard.appendChild(cardImg);
}
var userdivNome = document.createElement('div');
userdivNome.id = "diverso";
userTdinfo.appendChild(userdivNome);
var userdivVanity = document.createElement('div');
userdivVanity.id = "diverso";
userTdinfo.appendChild(userdivVanity);
var nome = "Nome: ";
var vanityurl = "Vanity Url: ";
userdivNome.innerHTML = nome + arrayEntita[u].__title__;
userdivVanity.innerHTML = vanityurl + arrayEntita[u].vanity_urls[0];
userTr.appendChild(userTdcard);
userTr.appendChild(userTdinfo);
userTable.appendChild(userTr);
}
wrapper.appendChild(userTable);
}
i dont know if this check:
if (i + 1 == arrayEntita.length)
BuildTable();
but else you have to check if alle responseses have returned before executing buildtable();
AJAX requests are asynchronous. They arrive at an unknown period during execution and JavaScript does not wait for the server to reply before proceeding. There is synchronous XHR but it's not for ideal use. You'd lose the whole idea of AJAX if you do so.
What is usually done is to pass in a "callback" - a function that is executed sometime later, depending on when you want it executed. In your case, you want the table to be generated after you receive the data:
function getData(callback){
//AJAX setup
var richiestaEntity = new XMLHttpRequest();
//listen for readystatechange
richiestaEntity.onreadystatechange = function() {
//listen for state 4 and ok status (200)
if (richiestaEntity.readyState === 4 && richiestaEntity.status === 200) {
//execute callback when data is received passing it
//what "this" is in the callback function, as well as
//the returned data
callback.call(this,richiestaEntity.responseText);
}
}
richiestaEntity.open("GET", "danielericerca.json"); //third parameter defaults to true
richiestaEntity.send();
}
function displayArrayCards() {
//this function passed to getData will be executed
//when data arrives
getData(function(returnedData){
//put here what you want to execute when getData receives the data
//"returnedData" variable inside this function is the JSON returned
});
}
As soon as you have made the ajax call, put all of the rest of the code inside the readystatechange function. This way, it will execute everything in order.
Edit: #Dappergoat has explained it better than I can.

document is undefined in Google URL harvester

I have code taken from Google to harvest URLs from Google. I saved it as filename.js. When I run the file it showed "'document' is undefined". The part of the code which is showing problem is
// ==UserScript==
// #name Google URL Harvester
// #namespace http://userscripts.org/scripts/show/42998
// #description Harvests URLs from a Google Search
// #include http://www.google.co.uk/
// #include http://www.google.com/
// ==/UserScript==
var btn_container;
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name == "btnG")
btn_container = inputs[i].parentNode;
}
function find_next_link(html) {
var url = html.match(/(<a href="[^"]+">)\s*<span[^>]+style="[^"]*background-position:\s?-76px\s/);
if (url == null)
return false;
var div = document.createElement("div");
div.innerHTML = url[1];
return div.firstChild.href;
}
function harvest(query_url, callback) {
ajax(query_url, function(e){
var als = e.match(/<a[^>]+class=l[^>]*>/g);
for (var i = 0; i < als.length; i++) {
urls.push(als[i].match(/href="([^"]+)"/)[1]);
}
var next_url = find_next_link(e);
if (next_url)
harvest(next_url, callback);
else
callback();
});
}
function ajax(url, callback) {
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
callback(req.responseText);
}
}
req.open("GET", url, true);
req.send("");
}
var new_button = document.createElement("input");
new_button.type = "button";
new_button.value = "Harvest URLs";
new_button.setAttribute("onsubmit", "return false;");
btn_container.appendChild(new_button);
var urls = [];
new_button.addEventListener("click", function(){
var query_url = unsafeWindow.document.forms[0].action + "?num=100&q="+escape(unsafeWindow.document.forms[0].q.value);
document.body.innerHTML = "<img src='http://oneworldwebsites.com/images/wheel%20throbber.gif' />";
harvest(query_url, function() {
document.body.innerHTML = urls.join("<br/>");
});
},false);
Here I have not defined document(if it is necessary). Can anybody please rectify the error in this code. Operating system is Windows 7.
I am saving this document to my desktop as harv.js and running it. Am I doing anything wrong?
Google like most websites updates their structure over time.
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name == "btnG")
btn_container = inputs[i].parentNode;
}
Needs to become
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].name == "btnK") //<<------G to K
btn_container = inputs[i].parentNode;
}
I can just guess that the error is thrown because you try to access the "input" element, before creating it later. Moreover you shouldn't use a html element as a identifier in JavaScript. You could also use Firebug to pinpoint the error.

Categories

Resources