Question

After going from my page to anther page by pressing a link, and than back to current page, than in call to xmlhttprequest from onload event, The js code of xhr.open and xhr.send is working, but the sever side code called by xhr is not running, and in xhr.onreadystatechange function the xhr.responseText is returning his old value.

In this scenario off comming back from another page, call to xmlhttprequest from document.onreadystatechange event is also not working OK.

The same code works OK when I call it from onload in the first page loading (before going to another page and returning), or when I call it from a button click.

Why the call to xmlhttprequest from onload event is not working OK when Back from another page?

I'm using Chrome.

Here is my code:

<script type="text/javascript">
function CallAJAX() {
    xhr = null;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else {
        xhr = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.onreadystatechange = AJAX_onreadystatechange;
    xhr.open("GET", '/MyPage.aspx', true);
    xhr.send(null);
}
function AJAX_onreadystatechange() {
    if (xhr.readyState == 4 && xhr.status == 200) {
        alert('xhr.responseText=' + xhr.responseText);
    }
}
window.onload = function () {
    //alert is working also after going to link and than back to current page
    alert('alert')
    //Call to xmlhttprequest from page onload event - is Not working OK - after going to link and than back to current page
    CallAJAX();
}
</script>
<!--here is the "link" mentioned in the above comment-->
<a href="http://www.google.com">link</a>
<!--Call to xmlhttprequest from button onclick event - is working OK-->
<input id="Button1" type="button" value="button" onclick="CallAJAX();" />

Update

I found the problem:

In some browsers, and in some circumstances, xhr brought the xhr.responseText value from browser cache, instead to call server.

Here is the solution:

This problem solved by adding unique query string param to url param of xhr.open. This guaranty that the ajax will avoid using the cache, and always hit the server, because with the unique param, the url is turned to unique in every call to xhr.open.

The unique value is produced by "new Date().getTime()" which returns the number of milliseconds between midnight of January 1, 1970 and now.

This is the solution code:

    xhr.open("GET", '/MyPage.aspx?uniqueParamVal=' + new Date().getTime(), true);

No correct solution

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top