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);
}
Related
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.
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.
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) {
// ....
I have the code (structure):
for (var x = 0; x < array1.length; x++){
(function(x) {
$.ajax({
url : "http://someurl1.ru/"+array1[x]+"/",
async: false,
success : function(someresult1){
array2.length = 0;
array3.length = 0;
var br = someresult1.split('<br>');
for (var b = 0; b < br.length-1; b++){
var space = br[b].split(" ");
array2.push(space[0]);
array3.push(space[1]);
}
for (var v = 0; v < array2.length; v++){
(function(v) {
$.ajax({
url : "http://someurl2.ru/"+array2[v]+"_"+array3[v]+"/",
async: false,
success : function(someresult2){
if(JSON.stringify(someresult2).search(some_array[x]) != -1){
$.ajax({
url : "http://someurl3.ru/"+array2[v]+"/"+array3[v]+"/"+some_another_array[x]+"",
async: false,
success : function(someresult3){
array4.push(someresult3);
}
});
}
}
});
})(v);
}
}
});
})(x);
}
I need to activate async in my request because it freezes my page and slowing down work of the program. There some explanation about program work:
1. Take first element of array1.
2. Creating link and sending request.
3. Taking result and doing some stuff with it.
4. Creating link and sending request.
5. Taking result and doing some stuff with it.
6. Creating link and sending request.
7. Taking result.
8. AND ONLY NOW we take second element of array1 and doing the same.
I need of synchronuous/continuous ajax requests (with "wait" result) in loop.
I just restructured the way you request URLs and the kind of callback. Alert me if something isn't right. Although, I didn't change the program actions and style. I'm really lazy to make that better.
Instead of loops I made a function to go consuming each array1 item, for example, and the same with the array2. When one request is done in one of these arrays, the next request starts if existent, else do nothing in array1 and when in array2 it just callbacks to the array1 to do the next array item request with the consume function.
var len = array1.length; // Memorize array1 length
function consume(i) {
var xhr = new XMLHttpRequest(); // Request
xhr.open("GET", "http://someurl1.ru/" + array1[i] + "/" , true);
xhr.onreadystatechange = function() {
if(this.readyState === 4) {
// Status 200 is success
if(this.status === 200) {
// `this` invokes the `xhr` object
// Your success block is here
successCallback(i, this.responseText);
// Consume next array1 items if length isn't ranged
}else{
// Error block is here; can be 403, 404, 500+, ... etc.
}
}
}
xhr.send()
}
consume(0);
function consume2(i, array2, array3, arrayLen, callback) {
var xhr = new XMLHttpRequest(); // Request
xhr.open("GET", "http://someurl2.ru/" + array2[i] + "_" + array3[i] + "/", true);
xhr.onreadystatechange = function() {
if(this.readyState === 4) {
// Status 200 is success
if(this.status === 200) {
// Your success block is here
if(JSON.stringify(xhr.responseText).search(some_array[i]) !== -1){
var xhr2 = new XMLHttpRequest(); // Request
xhr2.open("GET", "http://someurl3.ru/" + array2[i] + "/" + array3[i] + "/" + some_another_array[i], true);
xhr2.onreadystatechange = function() {
if(this.readyState === 4) {
// Status 200 is success
if(this.status === 200) {
// Your success block is here
array4.push(xhr2.responseText);
// Consume next array2 items
if(i < len)
consume2(++ i)
;else
callback()
}else{
// Error block is here; can be 403, 404, 500+, ... etc.
}
}
};
xhr2.send()
}
}else{
// Error block is here; can be 403, 404, 500+, ... etc.
}
}
}
xhr.send()
}
function successCallback(f, data) {
array2.length = 0;
array3.length = 0;
var br = someresult1.split('<br>');
for (var b = 0; b < br.length; b++){
var space = br[b].split(" ");
array2.push(space[0]);
array3.push(space[1]);
}
consume2(0, array2, array3, array2.length, function() {
if(f < len)
consume(++ f)
})
}
I'll update this code yet, but I don't understand what you surely want to do with it.
I've a small Greasemonkey script that doesn't include any random part, but its results change with each page reload.
I'm a noob and I'm probably doing something wrong, but I don't know what. I hope you'll be able to help me.
The code is too large and too poorly written to be reproduced here, so I'll try to sum up my situation:
I have a list of links which have href=javascript:void(0) and onclick=f(link_id).
f(x) makes an XML HTTP request to the server, and returns the link address.
My script is meant to precompute f(x) and change the href value when the page loads.
I have a function wait() that waits for the page to load, then a function findLinks() that gets the nodes that are to be changed (with xpath).
Then a function sendRequest() that sends the xhr to the server. And, finally handleRequest() that asynchronously (r.onreadystatechange) retrieves the response, and sets the nodes previously found.
Do you see anything wrong with this idea?
Using a network analyzer, I can see that the request is always sent fine, and the response also.
Sometimes the href value is changed, but sometimes for some links it isn't and remains javascript:void(0).
I really don't see why it works only half the time...
function getUrlParameterFromString(urlString, name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(urlString);
if (results == null) {
return "";
} else {
return results[1];
}
}
function getUrlParameter(name) {
return getUrlParameterFromString(window.location.href, name);
}
function wait() {
var findPattern = "//a";
var resultLinks = document.evaluate(findPattern, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
if (resultLinks == null || resultLinks.snapshotLength == 0) {
return setTimeout(_wait, 100);
} else {
for (var i = 0, len = resultLinks.snapshotLength; i < len; i++) {
var node = resultLinks.snapshotItem(i);
var s = node.getAttribute('onclick');
var linkId = s.substring(2, s.length - 1); // f(x)->x
sendRequest(linkId, node);
}
}
}
function sendRequest(linkId, nodeToModify) {
window.XMLHttpRequest ? r = new XMLHttpRequest : window.ActiveXObject && (r = new ActiveXObject("Microsoft.XMLHTTP"));
if (r) {
r.open("POST", "some_url", !0);
r.onreadystatechange = function () {
handleRequest(nodeToModify, linkId, r);
}
r.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
r.send(linkId);
}
}
function handleRequest(nodeToModify, num, r) {
if (r.readyState == 4) {
if (r.status == 200) {
console.log('handleRequest() used');
var a = r.responseText;
if (a == null || a.length < 10) {
sendRequest(num, nodeToModify);
} else {
var url = unescape((getUrlParameterFromString(a, "url")).replace(/\+/g, " "));
nodeToModify.setAttribute('href', url);
nodeToModify.setAttribute('onclick', "");
}
} else {
alert("An error occurred: " + r.statusText)
}
}
}
wait();
It looks like that script will change exactly 1 link. Look-up "closures"; this loop:
for (var i = 0, len = resultLinks.snapshotLength; i < len; i++) {
var node = resultLinks.snapshotItem(i);
var s = node.getAttribute('onclick');
var linkId = s.substring(2, s.length - 1); // f(x)->x
sendRequest(linkId, node);
}
needs a closure so that sendRequest() gets the correct values. Otherwise, only the last link will be modified.
Try:
for (var i = 0, len = resultLinks.snapshotLength; i < len; i++) {
var node = resultLinks.snapshotItem(i);
var s = node.getAttribute('onclick');
var linkId = s.substring(2, s.length - 1); // f(x)->x
//-- Create a closure so that sendRequest gets the correct values.
( function (linkId, node) {
sendRequest (linkId, node);
}
)(linkId, node);
}