My JS snippet includes a function that retrieves customer interest data from a specified URL using basic authentication. When calling this function in my HTML file, I am encountering an issue where the expected value is displayed only in one of the alerts and not in the console log.
function fetchData(customerRef) {
try {
var customerInterest = "";
var baseUrl = "https://test/";
var url = baseUrl + customerRef;
var username = "username";
var password = "password";
var request = new XMLHttpRequest();
request.open("GET", url);
request.setRequestHeader("Authorization", "Basic " + btoa(username + ":" + password));
request.send();
request.onload = () => {
if (request.status == 200) {
var guestJson = JSON.parse(request.response);
var sessions = guestJson.sessions || [];
var interest = sessions.filter(session => session.events)
.flatMap(session => session.events)
.filter(event => event.type === "SEARCH")
.map(event => event.arbitraryData.interest)[0];
customerInterest = interest;
alert("---" + customerInterest);
} else {
console.log(`error ${request.status} ${request.statusText}`);
}
}
alert(customerInterest);
return customerInterest;
} catch (error) {
console.error(error);
}
}
customerRef = "6a789727";
var interest1 = "";
interest1 = fetchData(customerRef);
console.log(interest1);