I have an even listener on a text box which triggers the NASearch function. I am utilizing a callback function so the ajax request should not run until after somevar3 is defined. somevar3[i].data is showing as undefined when called inside the ajax function though. Outside the ajax function somevar3[i].data is defined.
If i add async:false to the ajax function then everything runs great, but of course the UI suffers and I would like to avoid this. Any direction would be greatly appreciated.
function NASearch(query, callback) {
var data2 = "{\r\n \"ApiKey\": " + ak2 + "\r\n\r\n}";
xhr33 = new XMLHttpRequest();
xhr33.withCredentials = true;
xhr33.addEventListener("readystatechange", function() {
if (this.readyState === 4) {
if (typeof callback == "function") {
// apply() sets the meaning of "this" in the callback
callback.apply(xhr33);
}
//alert(OrgLegalName + "2")
}
});
xhr33.open("GET", "https://example.net/SmartSearch/NameAndAddressSearchAutoComplete?maxLength=31&clientAccountsOnly=True&accountPurposeTypeId=&institutionIdentityRecordId=&collectiveFundOnly=&query=" + query);
xhr33.setRequestHeader("accept", "application/json");
xhr33.setRequestHeader("x-api-key", ak2);
xhr33.setRequestHeader("authorization", "Basic " + cheetauth);
xhr33.setRequestHeader("cache-control", "no-cache");
xhr33.setRequestHeader("postman-token", "08c9199b-f6b4-22f1-bb8a-5d0dbdaffee0");
xhr33.send(data2);
}
NASearch(btn.value,
function() {
//while (theultheb.firstChild) theultheb.removeChild(theultheb.firstChild);
somevar3 = JSON.parse(xhr33.responseText).suggestions;
console.log(JSON.parse(xhr33.responseText));
// console.log(SFaccountresponse);
console.log(somevar3)
for (var i = 0; i < somevar3.length; i++) {
var identid = somevar3[i].data;
var identval = somevar3[i].value;
console.log(somevar3[i].data); //variable is defined here
$.ajax({
type: 'GET',
url: 'https://example.com/Organizations/Detail/' + somevar3[i].data,
success: function() {
console.log("EXISTS");
console.log(somevar3[i].data);
},
error: function() {
console.log("does not exist");
},
complete: function(xhr) {
var xhrresp = xhr.getResponseHeader('Content-Length');
if (xhrresp == 44) {
var link1b = document.createElement("a")
link1b.href = "https://example.com/Individuals/Detail/" + somevar3[i].data;
link1b.class = "k-link active";
link1b.appendChild(document.createTextNode(somevar3[i].value)); //undefined here
li1b = document.createElement("li");
li1b.class = "listyle ellipsis-overflow";
li1b.appendChild(link1b);
ul1b.appendChild(li1b);
} else {
var link1b = document.createElement("a")
link1b.href = "https://example.com/Organizations/Detail/" + somevar3[i].data; //undefined here
link1b.class = "k-link active";
link1b.appendChild(document.createTextNode(somevar3[i].value)); //undefined here
li1b = document.createElement("li");
li1b.class = "listyle ellipsis-overflow";
li1b.appendChild(link1b);
ul1b.appendChild(li1b);
}
}
});
}
}
);