I need assistance in building a JS loop to loop through a list of user selected value, I am a bit new to the topic.
- I have a UI that allows a user to select a dog breed name (A user may select multiple)
- The selection is then stored in a variable that I pass onto my JS script
- In my JS script, I then need to loop through these selected values to retrieve image URLs through Bing API image search, And then pass those URLs back to the UI variable.
My script works perfect when one item is selected by the user but I am struggling to cater for multiple selections by the user.
var imageToSearchQlikSenseVariable = 'vImageToSearch';
var imageKeyQlikSenseVariable = 'vImageKey';
var bingImageApiBaseUrl = "https://bing-image-search1.p.rapidapi.com/images/search?q=";
var bingImageApiHost = "bing-image-search1.p.rapidapi.com";
var bingImageApiKey = "***************";
var bingImageApiAdditionalParams = "&count=1&safeSearch=Strict";
var data = null;
var xmlHttpRequest;
//allow the JavaScript code the read/write access to the QlikSense app
function getCurrentQlikSenseApp() {
var appId = qlik.currApp().id;
return qlik.openApp(appId);
}
//returns the list of selected values from the OEM field stored in the QlikSense variable
async function getImageToSearchString() {
var app = getCurrentQlikSenseApp();
var image;
await app.variable.getContent(imageToSearchQlikSenseVariable, function (reply) {
image = reply.qContent.qString;
});
return image;
}
//will allow us to make HTTP requests for the image search in JavaScript
function initiateXmlHttpRequest() {
xmlHttpRequest = new XMLHttpRequest();
xmlHttpRequest.withCredentials = true;
}
//retrieve all URLs that corresponds with the selected OEM names and store those URLs into QlikSense
function setImageUrlQlikSenseVariableWhenXmlHttpRequestIsDone() {
var app = getCurrentQlikSenseApp();
xmlHttpRequest.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
const responseJson = JSON.parse(this.responseText);
const imageUrl = responseJson.value[0].contentUrl;
app.variable.setStringValue('vImageUrl', imageUrl);
}
});
}
//building a complete image URL string
function getEncodedUri(imageToSearch) {
var uriToGet = bingImageApiBaseUrl + imageToSearch + bingImageApiAdditionalParams;
return encodeURI(uriToGet);
}
//sets the value of an HTTP request header
function addHeaderToRequest() {
xmlHttpRequest.setRequestHeader("x-rapidapi-host", bingImageApiHost);
xmlHttpRequest.setRequestHeader("x-rapidapi-key", bingImageApiKey);
}
//execute all the above function respectively to allow for the retrieval of the selected image URL values to be displayed in QlikSense
async function execute() {
var imageToSearch = await getImageToSearchString();
initiateXmlHttpRequest();
setImageUrlQlikSenseVariableWhenXmlHttpRequestIsDone();
xmlHttpRequest.open("GET", getEncodedUri(imageToSearch));
addHeaderToRequest();
xmlHttpRequest.send(data);
}
execute();