Technologies:
Tolerim
23 days ago
How can I use Ajax to append 3 images to HTML through a single HTTP GET request?
"use strict";
$(function () {
const MIN = 0;
const MAX = 9;
let numeroImage = Math.floor(Math.random() * 8) + 1; // Random number
console.log(numeroImage);
requeteImage(numeroImage);
// Move to the previous image
$("input[type=button]:eq(0)").on("click", () => {
if (numeroImage - 1 >= MIN) { numeroImage -= 1; }
else { numeroImage = MAX };
requeteImage(numeroImage)
});
// Move to the next image
$("input[type=button]:eq(1)").on("click", () => {
if (numeroImage + 1 <= MAX) { numeroImage += 1 }
else { numeroImage = MIN };
requeteImage(numeroImage)
});
function requeteImage(numeroImage) {
$(".images").html(""); // Remove previous images
for(let i = -1; i < 2; ++i) {
$.get("http://198.245.55.77/mars/camera.php", { image: numeroImage + i })
.done((data) => {
$(".images").append('<img src="data:image/png;base64,' + data + '">');
})
.fail((error) => {
console.log(error);
});
}
}
});
Answers(1)
Tolerim
23 days ago
Verified Answer
Yes, you are correct that the problem is because the requests are asynchronous and not guaranteed to finish in the order you expect.
One way to fix this without using promises is to use a counter to keep track of how many requests have finished, and only append the images to the DOM once all three requests have completed. Here's an example of how you could modify your requeteImage function to use this approach:
function requeteImage(numeroImage) {
$(".images").html(""); // Supprimer les images précédentes
let requestCount = 0;
let imageData = [];
const handleResponse = (data) => {
imageData.push(data);
requestCount++;
if (requestCount === 3) {
for (let i = 0; i < 3; i++) {
$(".images").append(`<img src="data:image/png;base64,${imageData[i]}">`);
}
}
};
$.get("http://198.245.55.77/mars/camera.php", { image: numeroImage - 1 })
.done((data) => {
handleResponse(data);
})
.fail((erreur) => {
console.log(erreur);
});
$.get("http://198.245.55.77/mars/camera.php", { image: numeroImage })
.done((data) => {
handleResponse(data);
})
.fail((erreur) => {
console.log(erreur);
});
$.get("http://198.245.55.77/mars/camera.php", { image: numeroImage + 1 })
.done((data) => {
handleResponse(data);
})
.fail((erreur) => {
console.log(erreur);
});
}
In this modified function, we keep track of the number of requests that have been made and store the image data in an array. We define a new function handleResponse to handle the response from each request. This function adds the data to the imageData array and increments the requestCount variable. Once all three requests have completed, we iterate through the imageData array and append the images to the DOM.
This approach should ensure that the images are in the correct order, regardless of how long each request takes to complete.