Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Internet Explorer 7 Ajax links only load once

I'm writing an application and I'm trying to tie simple AJAX functionality in. It works well in Mozilla Firefox, but there's an interesting bug in Internet Explorer: Each of the links can only be clicked once. The browser must be completely restarted, simply reloading the page won't work. I've written a very simple example application that demonstrates this.

Javascript reproduced below:

var xmlHttp = new XMLHttpRequest();

/*
item: the object clicked on
type: the type of action to perform (one of 'image','text' or 'blurb'
*/
function select(item,type)
{

    //Deselect the previously selected 'selected' object
    if(document.getElementById('selected')!=null)
    {
        document.getElementById('selected').id = '';
    }
    //reselect the new selcted object
    item.id = 'selected';

    //get the appropriate page
    if(type=='image')
        xmlHttp.open("GET","image.php");
    else if (type=='text')
        xmlHttp.open("GET","textbox.php");
    else if(type=='blurb')
        xmlHttp.open("GET","blurb.php");

    xmlHttp.send(null);
    xmlHttp.onreadystatechange = catchResponse;

    return false;

}
function catchResponse()
{
    if(xmlHttp.readyState == 4)
    {
        document.getElementById("page").innerHTML=xmlHttp.responseText;
    }

    return false;
}

Any help would be appreciated.

like image 394
stillinbeta Avatar asked Oct 28 '08 21:10

stillinbeta


2 Answers

This happens because Internet Explorer ignores the no-cache directive, and caches the results of ajax calls. Then, if the next request is identical, it will just serve up the cached version. There's an easy workaround, and that is to just append random string on the end of your query.

 xmlHttp.open("GET","blurb.php?"+Math.random();
like image 83
TJ L Avatar answered Sep 23 '22 20:09

TJ L


It looks like IE is caching the response. If you either change your calls to POST methods, or send the appropriate headers to tell IE not to cache the response, it should work.

The headers I send to be sure it doesn't cache are:

Pragma: no-cache
Cache-Control: no-cache
Expires: Fri, 30 Oct 1998 14:19:41 GMT

Note the expiration date can be any time in the past.

like image 39
pkaeding Avatar answered Sep 21 '22 20:09

pkaeding