after I excute that code in the firefox console, I receive an erorr thay says" ReferenceError: abc is not defined". how do I fix that to make it work? its looks like after the IF ends, the FOR forgets the value of the varirable "abc". what to do? please help
for (i = 0; i < 10; i++) {
if (i == 0 || i == 5) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var str = this.responseText;
var text = str.split('?id = "')[1];
var abc = text.split('";')[0];
}
};
xhttp.open("GET", "http://example.com", true);
xhttp.send();
}
fetch("http://www.example.com/post.php", {
"credentials": "include",
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0",
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5",
"Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "XMLHttpRequest"
},
"referrer": "http://www.example.com/index.php",
"body": "id=" + abc + "",
"method": "POST",
"mode": "cors"
});
}
You can't access abc
outside the XHR onreadystate
function. It's a local variable, and it's also assigned asynchronously. So you need to perform the fetch()
calls from there.
So you should use nested loops. One loop performs the two GET
requests, and then you do 5 POST requests in the callback function of that.
You can do everything with Fetch instead of mixing XHR and Fetch. You should use encodeURIComponent(abc)
to ensure it's encoded properly.
for (let i = 0; i < 2; i++) {
fetch('http://example.com', {
method: "GET"
})
.then(response => response.text())
.then(str => {
let text = str.split('?id = "')[1];
let abc = encodeURIComponent(text.split('";')[0]);
for (let j = 0; j < 5; j++) {
fetch("http://www.example.com/post.php", {
"credentials": "include",
"headers": {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; rv:68.0) Gecko/20100101 Firefox/68.0",
"Accept": "*/*",
"Accept-Language": "en-US,en;q=0.5",
"Content-Type": "application/x-www-form-urlencoded",
"X-Requested-With": "XMLHttpRequest"
},
"referrer": "http://www.example.com/index.php",
"body": "id=" + abc,
"method": "POST",
"mode": "cors"
});
}
});
}