I have the following jquery code :
function ajax_set_thumbnail(item_id, full_path)
{
xhttp = new XMLHttpRequest();
var params = 'full_path=' + full_path;
xhttp.open("POST", "/ajax/set_thumbnail/" + item_id + "/", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(params);
var timestamp = new Date().getTime();
$('#thumbnail').attr('src', $('#thumbnail').attr('src') + '?' + timestamp )
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
My goal is to update a thumbnail then to reload the new thumbnail (same name just the picture change).
The code works, but not as I would like to. I want to update the picture and then to reload it. But when I checked the trace, the reload comes before the update is done. So I have no change on the image.
How could I do ?
Not an expert but if the image reload happens before the AJAX request to update the picture is completed, you should use the
onreadystatechangeevent of theXMLHttpRequestobject. This event is triggered every time the ready state of theXMLHttpRequestchanges. By checking if the request is completed and successful (readyState 4 and status 200), you can ensure that the code to reload the image is executed only after the picture has been updated on the server.Here's how you can modify your
ajax_set_thumbnailfunction to achieve this:This modified version of your function waits for the AJAX request to successfully complete before proceeding to update the image's
srcattribute to force a reload. It also ensures that any existing query parameters are removed from the image'ssrcbefore appending the new timestamp. This is done by splitting thesrcstring at the?character and only using the first part (the original URL without query parameters) before appending the new timestamp query parameter.This code does not include error handling.