Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery $.ajax() function problems with image caching

I have a very wierd problem. I created a login system with ajax and php.
When the userprofile is loaded the user also has a picture.
Then when i try to change the picture with iframe on a modal dialog and press Save the image should be changed in the user profile without page refresh.
I use

$(".userPicture").attr("srs","Users/"+username+"/profileimg.jpg");

I also tried

$(".imgContainer").html("<img src='Users/"+username+"/profileimg.jpg' class='userPic' >");

Still not working

It seems that the cached image is loaded in the profile picture even if i upload new picture.
The problem is that i want to do this with ajax without page refresh.
If i reload the page the picture is changed. Any help please. Also how can i verify specific output from $.ajax function in the success function for example

$.ajax({
    type: 'POST',
    url: baseURL,
    dataType: 'html',
    cache: false,
    data: {
        action: "LOGIN",
        username:username,
        password:password
    },
    success: function(data) {
        if (data == "empty") {
           showError("Error: Wrong Username or Password","loginTab");
        }
        else {

        }
    }
});

When i do datatype json i can verify my data if its empty but when i do html i cant. Is there any other way how can i handle this situation.

like image 794
aygeta Avatar asked Feb 02 '26 05:02

aygeta


1 Answers

Add a cache-busting random value to the url, forcing the server to retrieve a fresh copy:

"Users/"+username+"/profileimg.jpg?cachebuster=" + new Date().getTime()

The webserver will ignore the query string since it's just fetching a jpg, and the query string will force the browser to see it as a 'new' request, so it'll bypass the cache and hit the server.

like image 164
Marc B Avatar answered Feb 03 '26 17:02

Marc B



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!