I am pretty new to php & Wordpress with a basic knowledge of html/css/js. I have a php function in my functions.php that gets me the image url's and image titles of my websites media library and puts them in arrays.
Then, through Ajax, I receive these arrays to use in javascript. Like so:
const wp_image_url = [];
const wp_image_id = [];
$.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'post',
data: {
action: 'mv_get_images_id',
},
dataType: "json",
success: function(data) {
for (let i = 0; i < data.length; i++) {
wp_image_id.push(data[i]);
}
console.log(wp_image_id);
},
fail: function() {
console.log('failed to load image data');
},
});
$.ajax({
url: '/wp-admin/admin-ajax.php',
type: 'post',
data: {
action: 'mv_get_images_url',
},
dataType: "json",
success: function(data) {
for (let i = 0; i < data.length; i++) {
wp_image_url.push(data[i]);
}
console.log(wp_image_url);
},
fail: function() {
console.log('failed to load image data');
},
});
console.log('these are below' + wp_image_id);
console.log('these are below' + wp_image_url);
console.log('init.js end');
I then want to use the wp_image_id and wp_image_url variables in a later items.js script to generate div's with images in them based on the image url and titles based on the id. Like a Masonry gallery.
However, when I look at the network tab in my browser I see that the ajax request takes longer to happen causing the other js files to execute before the array's are filled with the necessary information.
the console when loading the site
I wonder if I can make it so the rest of the javascript only begins to run after the ajax requests are complete. I'm also kind of wondering if i'm going the right way in general.
To summarize I essentially want to get the image information of all my images in my wp media library, to then use this info to generate a masonry grid layout of images.