Pushstate after Ajax



Tested AJAX recently.

I have a productpage. Here I show a large productimage and information about the product. On the same page you can choose other colors for the same product. And if you change to a different color, the big picture and the information about that product/color will be replaced with the new selected color. Thanks to AJAX, this works fine without reloading the page. I request the new color that has been selected, and then I change the innerHTML with the respons that I get from AJAX.

The problem that arose here was that when you clicked back, there was of course nothing to go back to. And if the user wants to save the page with the new color, I also needed to add a new url and not just add new content . This led me to "history.pushstate"...

I do not know how to solve this at best but I did like this ...

When I got back the html for the new color through AJAX response, I saved this html to an object that I used with history.pushstate. This object is associated with a the new url that I also pass along with the object when I use "history.pushstate" ... At first, only the url and not the content were changed.

Then I tested "onpopstate". When this event occurred I let it change the innerHTML of the element holding the old content, to the HTML that I had saved in the object when using history.pushstate.

It doesnt matter how many colors I change to. I create new objects with history.pushstate on each AJAX request, which I can then reuse instead of having to make a new request when I go back or forth

So I have some thoughts. How can you do this differently? More correct maybe?

First of all, it does not look good if you write history.state in the console and see a object with massive HTML.

Secondly, I'm guessing that it can slow down the website after a while if you keep collecting a lot of these objects that contains saved html

I also read somewhere that you may be able to use cache for my mainproblem here or re-render in any way?

I hope you guys can help me a little here. I appreciate all the advice I can get



Hey there!

Your data from which the new information originates from (the color) is all you need to get the other data.
Your server should handle caching properly. So it should be no problem to request the data again and handle the request as if the user was just landing on the page.
You should only store the color. Preferably in the URL. You could use a query string: products-biz.com/products/2?color=#FF00DD And then fetch the data. History push-state should only handle fetching that required data then (Similar to how PJAX works).

Hope this approach helps.


Thanks for your answer. So my options are either to cache... Or save the response to the pushstate-object which I then can use to restore the page with onpopstate.

Why would caching be a better option do you think?


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.