Reputation: 543
I am facing one issue
I am uploading profile picture
It saved to s3 bucket and it returns url
But I am facing one issue
Once the picture updated it need to refresh the page for showing new image
I need to update that div once the picture get updated
Here is my Ajax call
$("#profile-pic-upload").change(function () {
var input_detail = this;
console.log(input_detail);
var data = new FormData();
var file = this.files[0];
data.append("file", file);
$.ajax({
type: 'POST',
data: data,
contentType: false,
processData: false,
url: $("#profile-file-upload").data('action'),
cache: false,
success: function (data, status) {
if (data['status'] == true) {
toastr.success(data.msg);
$('#imagePreview').css('background-image', 'url('+data.avatar+')');
}
else {
toastr.error(data.msg);
}
}
});
});
Here is my HTML
<div class="avatar-preview">
{% if user_profile.avatar %}
<div id="imagePreview" style="background-image: url('{{user_profile.avatar}}');"></div>
{% else %}
<div id="imagePreview" style="background-image: url('{% static 'assets/img/user-64x.png' %}');"></div>
{% endif %}
</div>
In the above code I am getting image url from data.avatar
But my issue is it only getting updated only the once
For example if there is no image updated it getting updated
If there is a image in user profile I updated to new one Then it upload to s3 bucket but it will not display in the div. I need to refresh the page for displaying it there
Upvotes: 1
Views: 117
Reputation: 18002
In your success callback change your:
$('#imagePreview').css('background-image', 'url('+data.avatar+')');
to:
var randomId = new Date().getTime();
$('#imagePreview').css('background-image', 'url(' + data.avatar + '?random=' + randomId + ')');
You can use whatever randomId you want to force the image being refreshed, I've chosen to use the current timestamp.
Changing just one parameter like this one forces the web broser to reload an image, javascript... and not use the one in cache.
Upvotes: 3