ahCodes ahCodes - 6 months ago 68
Javascript Question

How to change the URL then refresh the page (Safari/Firefox)

I have a simple ajax call written in jQuery. It passes a string to the server and the server returns some json data.

$.ajax({
url: ...,
dataType: 'json',
success: function(data) {
for (var d in data) {
var title = $('<a onClick="location.reload()" href="/player#v='+ data[d].content.id+'" "><p>'+ name +'</p></a>');
}
}
});


What I want to happen is when a user clicks on that link ("title"), for the page to reload at that new URL. Keep in mind, the current page is the page it wants to redirect to, but with a new hash in the URL instead (essentially, reloading all the content on the page with new content). This works perfectly in Chrome. In Safari and Firefox, it simply reloads the current page, no matter which link you click on in the column (there's multiple links with different URIs). If I take out the onClick event, the URL just changes, but the page doesn't reload.

I've tried changing the onClick event to a custom function using window.location.replace('new url here'), but it simple does nothing. Any help is appreciated.

Answer

After attempting numerous solutions, both in the context of onClick events and changing directly within the HTML of the ajax call, I found a much easier solution native to jQuery.

Outside of the ajax call, I used jQuery's built-in 'onhashchange' event:

$(window).on('hashchange', function() {
        location.reload();
});

And then the html within the ajax call looks like the following:

var title = $('<a href="/player#v='+data[d].content.id+'"><p>'+ name +'</p>   </a>');

Previously, in the code in the question, in Chrome the page would reload once clicking an item and refresh the page with the new content. But in Safari and FireFox, the page reload came before the new content was triggered, therefor reloading the page with the same content.

Now, the new content (the hash in the URL) is forced to be recognized and only then does the page reload. Tested and works in Chrome, FireFox and Safari.