dougoftheabaci
dougoftheabaci

Reputation:

Update URL on AJAX call?

Right now the biggest issue I'm having with using AJAX is the fact that if I use AJAX on a page, go to another page, then use the browser's back button to go back anything that was changed with AJAX is gone.

I've thought about using the jQuery Addresss plugin to solve that problem but I don't like how it only amends the URL with "#whatever.html" instead of changing it completely.

Ideally, what I would like is to have the URL go from: "www.example.com/p:2/" to "www.example.com/p:3/" when I make the relevant AJAX call.

Is this at all possible?

Upvotes: 24

Views: 55455

Answers (5)

SolutionYogi
SolutionYogi

Reputation: 32233

Nope, this is not possible. Update: It is now possible via the HTML5 History API - see razbakov's answer.

I hope you realize that you are trying to address an extremely difficult problem.

Let's say your url looks like

http://example.com/mypage/

If you change the window location programmatically to

http://example/mypage/1/

Browser will take over and try to navigate to that page, there goes your fancy ajax code!

So what's the alternative? You use URL fragment.

Let's say you have a URL like this,

http://example.com/anotherpage/#section

Browser will first load http://example.com/anotherpage/ and try to find an anchor named 'section' and scroll to that location. This behavior is exploited by the 'Addresses' plugin. This is similar to how those 'Scroll To Top' links work.

So if you are on the page

http://example.com/mypage/

and change the URL to

http://example.com/mypage/#1

Browser will not load new page but rather try to find anchor named '1' and scroll to that anchor.

Even if you have managed to add fragments to the URL, it doesn't mean the work is done. If the user presses the back button, DOM will be reset and you will have to parse those fragments and recreate the DOM. It's definitely non-trivial.

Upvotes: 20

Syed Shahjahan
Syed Shahjahan

Reputation: 119

After making AJAX call, we can update the Client URL using history.pushState. Please find the below syntax and example

Syntax: history.pushState(obj, obj.Title, obj.Url);

Example:

var url = "http://example.com/mypage/" + "newParameter=newValue"
history.pushState(undefined, '', url);

Upvotes: -1

thd
thd

Reputation: 2430

This problem can be solved using history.js. https://github.com/browserstate/history.js

Upvotes: 5

duckegg
duckegg

Reputation: 1389

pjax handles this gracefully in modern browser.

Upvotes: 1

Aleksey Razbakov
Aleksey Razbakov

Reputation: 634

It's possible with HTML5. You can test as example GitHub or Vkontakte site.

The best answer is here: Change the URL in the browser without loading the new page using JavaScript

It says that you can use history.pushState function for those purposes. But this solution will only work in HTML5 compatitable browsers. Otherwise you need to use hash-method.

Upvotes: 23

Related Questions