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 onreadystatechange
event of the XMLHttpRequest
object. This event is triggered every time the ready state of the XMLHttpRequest
changes. 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_thumbnail
function to achieve this:
function ajax_set_thumbnail(item_id, full_path) {
var xhttp = new XMLHttpRequest();
var params = 'full_path=' + encodeURIComponent(full_path);
xhttp.open("POST", "/ajax/set_thumbnail/" + item_id + "/", true);
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Use onreadystatechange to detect when the AJAX request is complete
xhttp.onreadystatechange = function() {
// Check if the request is complete and was successful
if (this.readyState == 4 && this.status == 200) {
// This code will run after the thumbnail has been updated on the server
// Append a timestamp query parameter to the image src to force the browser to reload it
var timestamp = new Date().getTime();
$('#thumbnail').attr('src', function() {
// Remove any existing timestamp query parameter before adding the new one
var src = $(this).attr('src').split('?')[0];
return src + '?' + timestamp;
});
}
};
// Send the AJAX request
xhttp.send(params);
}
This modified version of your function waits for the AJAX request to successfully complete before proceeding to update the image's src
attribute to force a reload. It also ensures that any existing query parameters are removed from the image's src
before appending the new timestamp. This is done by splitting the src
string 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.