I have tried to simplify the code, but here I am making requests to the api, it all works fine until I try to call function 5 in function 4, where it instead puts the data received by the api into function2.
Has anyone got any idea of how to stop this happening?
var xhr = new XMLHttpRequest();
var counter = 0;
window.onload = function() {
var add_button = document.getElementById('add_button');
add_button.addEventListener('click', function1);
var function1 = function() {
counter++;
xhr.addEventListener('load', function2);
var url = 'https://api.example.org/search';
console.log(url);
xhr.open("GET", url);
xhr.send();
};
var function2 = function() {
var data = JSON.parse(this.response);
console.log(data);
function3();
};
var function3 = function() {
for (var i in searchArray) {
var Url2 = 'https://api.example.org/search2';
xhr.open("GET", Url2);
xhr.addEventListener('load', function4);
xhr.send();
};
};
var function4 = function() {
var data2 = JSON.parse(this.response);
if (counter === 3) {
var url3 = 'https://api.example.org/search3';
xhr.open("GET", url3);
xhr.addEventListener('load', function5);
xhr.send();
};
};
var function5 = function() {
var data3 = JSON.parse(this.response);
};