The issue with the provided code is that the images variable is being assigned a value asynchronously inside the $.getJSON callback function. However, the dialogDefinition.addContents function is being called synchronously before the images variable is assigned a value. Therefore, the images variable is still undefined when it is being passed to the html property of the foo element.
To solve this issue, we need to move the dialogDefinition.addContents function inside the $.getJSON callback function, so that it is called only after the images variable is assigned a value. Here's an updated code example:
CKEDITOR.on('dialogDefinition', function (ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if (dialogName == 'image') {
dialogDefinition.dialog.resize(700, 500);
var API_KEY = 'adfasdf';
var URL =
'https://pixabay.com/api/?key=' +
API_KEY +
'&q=' +
encodeURIComponent('red roses');
$.getJSON(URL, function (data) {
if (parseInt(data.totalHits) > 0) {
var images = '';
$.each(data.hits, function (i, hit) {
images +=
"<img class='img' src='" + hit.pageURL + "' alt='" + hit.tags + "'>";
});
dialogDefinition.addContents({
id: 'uploadTab',
label: 'Upload',
elements: [
{
type: 'text',
id: 'uploadField',
label: 'Upload',
},
{
type: 'html',
id: 'foo',
html: images,
},
],
});
} else {
console.log('No hits');
}
});
}
});
In this updated code, we have moved the dialogDefinition.addContents function inside the $.getJSON callback function. We have also initialized the images variable as an empty string before the $.each loop, and concatenated the image tags to it inside the loop. Finally, we have added the alt attribute to the img tag to provide some context to the image.