Back

Technologies:

javascriptjavascript
jqueryjquery
avatar
Tolerim
23 days ago

How can I use Ajax to append 3 images to HTML through a single HTTP GET request?

My task is to display a 108-degree POV on my webpage by fetching three consecutive images from a set of ten located at URL: "http://198.245.55.77/mars/camera.php". Since each image has a 36-degree POV, I need to ensure that the images are displayed correctly and in order.

When the page loads, function requeteImage is executed, which displays three images with consecutive indexes. However, since the requests are asynchronous, the images may not be in order. I want to know if there is a way to fix this without using promises, as I am not yet proficient with them.

Here is my code:

"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);
            });
        }
    }
});
I attempted to make three separate requests instead of using a for loop and placed them in if statements to execute only after the previous request is done. However, this has not resolved the issue.

Thank you for any assistance you can provide!

Answers(1)
avatar
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.
;