Robert W. Hunter
Robert W. Hunter

Reputation: 3003

window.location.replace not working if the same page is reloaded

I'm trying to refresh page on Ajax success.

var lastId = "#" + id;
window.location.replace("/myurl" + lastId);

It is writing the correct URL to my browser but I don't see the changes made. If I refresh (F5) the page, I see the changes correctly because the ajax was correctly sended.

So I think that page won't force refresh if the url is the same.

In this example, I'm already on http://mypage.com/myurl, it is supossed to redirect me to http://mypage.com/myurl#38174 for example, so my browser will focus the DOM element with id="38174".

As I said, if I submit the ajax request, my url changes to http://mypage.com/myurl#38174 and focus id="38174" but I don't see the changes made to that element on my DB, if I hit F5, it focus the same element but with the changes correctly shown.

Why is this hapening?

I've also tried with window.location.href and window.location without success.

If I use window.location.replace('http://stackoverflow.com'); it's sending me to this website correctly...

So I think the problem is when replacing with the same url + some hashtag... maybe?

As I've said, in this case in particular we need to refresh after an AJAX request only if it's a success, yes, it sounds weird and counterproductive but it is needed.

Upvotes: 5

Views: 12082

Answers (2)

Pieter De Schepper
Pieter De Schepper

Reputation: 476

Updating a hash from the URL will not trigger a new pageload.

You'll need to listen to the hashchange event in javascript to initiate your ajax call, without the need for your page to refresh. This will give you a better user experience

If you use jQuery, you can use something like:

$(window).on('hashchange',function(){ 
    //Do ajax call here
});

Upvotes: 0

weir
weir

Reputation: 4761

var lastId = "#" + id;
window.location.replace("/myurl" + lastId);
window.location.reload();

Upvotes: 5

Related Questions