Phil Cross
Phil Cross

Reputation: 9302

Javascript redirect or reload

I have an ajax method which submits data over ajax. The server then responds with a URL to load. Most times the URL will be different to the one on which the request was made, but sometimes the URL is the same.

Either way, I want the page to go to the intended url, even it's just reloading the page.

I've tried the window.location.href = '' method, but if the current url is the same as the intended url, nothing happens.

I've tried the window.location.replace(url) method, but that doesn't reload the page if current === intended.

I've tried the window.location.reload(true) method, but that's only good if the current url is the same as the intended url.

I've tried to compare the intended URL to the current url and do either a reload or a href method, but this has problems as well. If I click on a bootstrap tab, the hash doesn't appear in the URL, so the current url value is actually incorrect.

For your reference, this is/was my comparison:

if(window.location.href === response.intended) {
    window.location.reload(true);
} else {
    window.location.replace(response.intended);
}

All I want to do, is force the browser to redirect to an intended URL, or reload the current page depending on current URL vs intended URL.

Upvotes: 0

Views: 136

Answers (3)

rajuGT
rajuGT

Reputation: 6404

As discussed over comments, I think this is due to the # character in the url, which makes the browser to move to particular section of the page like <a href='33347913'> tag.

var index = response.intended.indexOf('#');
if(index >= 0) {
    response.intended = response.intended.substr(0, index);
}
window.location.href = response.intended;

Upvotes: 0

charlietfl
charlietfl

Reputation: 171679

Add window.location.hash to the new url for comparison. If there isn't one it will return an empty string

if(window.location.href === response.intended + window.location.hash) { 

Upvotes: 1

Lee Taylor
Lee Taylor

Reputation: 7984

To ensure your page isn't being cached, add a random number to the end of the url:

window.location.replace(response.intended + "?rnd" + Math.random() );

Upvotes: 3

Related Questions