Tom
Tom

Reputation: 43

Why is this html not updating using jQuery?

I have a standard jQuery ajax function:

$.ajax({ 

    // blah blah...

    success: function(data) 
    {
        if(data) 
        {
            $('.title').text(data.title);
            $('.description').text(data.description);
            if (data.image) 
            {
                $('div#image').html('<a href="'+data.image+'" class="button">View Image</a>');                      
            }
        }
    }

});

The server response is a json object. data.image returns a url of the image location. I am simply sticking it in a link and sticking that inside a div.

This ajax call runs every time the user clicks a "next" or "prev" button on a gallery. The problem is, after the first time that link is loaded, it stays cached or something because even when I click next or prev and everything else updates like title and description, that link won't update. It always points to the first image.

The really weird thing is, if I replace this:

$('div#image').html('<a href="'+data.image+'" class="button">View Image</a>');

with:

$('div#image').html(data.image);

it works fine, a new url is loaded each time the ajax call runs. But if I put that inside some html, then it loads once and stays cached or something.

Does anyone know why this may be happening?

Upvotes: 2

Views: 1161

Answers (2)

Marlin
Marlin

Reputation: 749

Tom, there isn't enough information here to really determine what's wrong but if simply referencing data.image by itself works fine, why not reword your function to use it that way.

$.ajax({ 
    // blah blah...
    success: function(data) 
    {
        if(data) 
        {
            $('.title').text(data.title);
            $('.description').text(data.description);
            if (data.image) 
            {
                $('div#image a').attr('href',data.image);                      
            }
        }
    }
});

Upvotes: 2

MoXplod
MoXplod

Reputation: 3852

$.ajaxSetup({ cache: false });

Try putting that somewhere in your script before the call

Or in your $.ajax call put a parameter

cache: true

Upvotes: 1

Related Questions