How to maintain the page state when browser back button is clicked? - javascript

I have a page with Client side paggination and Filtration. The page lists around 200-300 prouducts.
The page contains some filters like Category,Manufacturer and Weight.
Clicking upon any of the page number or filter, I am manupulating the page content on client side using Jquery.
Everything is working fine till this step. Now there is a usecase where I am facing problem.
Lets say a user comes to our product listing page and click on some of the filters and gets a list of products.
Now he clicks on a particular product , which redirects him to the product page to view the details of the product.
But now when the user clicks on the back button , the user gets the page with the intial state without any filter selected.
Is there any way user will get the page with the filters previously selected on clicking the back button?

You can use some of the following to store data across multiple pages.
Store data in cookies.
Store data in local storage.
Store data in the session on the server.
Make the data part of your URL (use hash or query string for the filter parameters). Note that changing query string causes page reload.
If using cookies, local storage, or hash, you'll need to add JavaScript code to your page that loads and applies the stored data on page load.

There is a number of ways to do this:
If you are dealing with html5 history and a single-page application, then you are not reloading the page. But based on your question, I assume this is not what you are dealing with.
Store something in the URL. For an example of this, look at the filters on TotalHockey, e.g. http://www.totalhockey.com/Search.aspx?category_2=Sticks%2fComposite%20Sticks&chan_id=1&div_main_desc=Intermediate&category_1=Sticks so when you go backwards, the URL contains the entire state.
Use localstorage, if you have a browser that supports it.
use cookies with the $.cookie API
Store it on the session in the server.

You can store the Search Filter Data in session just after submitting on the filter input and on each ajax request (Loading your product listing), you can check the search filter inputs stored in the session and show the data according to them. If search session is empty then show whole listing.
You can also store the full ajax request URL (if GET method is used) in the session after searching the record and hit that particular URL again after coming back from product detail page.

Related

JavaScript: how to pass additional information to source page?

I have a website and when a user follows an internal link I would like to pass some extra information to a new page, so JavaScript on the destination page could do some useful highlighting.
There is an option to pass that information via the link parameters (GET), but it will generate lots of virtually duplicate pages and break pretty URLs concept. Another way is to make a webapp using AJAX, but it will also bound content to a single URL.
How can I transparently pass some information to the new page during navigation w/o messing with site's URL structure?
You could store the data in local storage or session storage, and retrieve it again on the destination page.
So you have a few options.
Form Submission
First option post a form with the data. Add a hidden form, on the anchor click capture the click event, set the hidden fields with the values you want to send to the next page, and submit the form. On the next page, read the post parameters in the backend and update the page.
Local Storage
On click of the anchor, set localStorage to the values you want to appear on the next page. When the next page loads, read the localStorage values and update the page. Note: The server will not have access to the values
Ajax with pushState
Use Ajax to submit the form. When the Ajax call returns, use window.history.pushState to update the url with whatever url you want to be displayed to the user.
One of the options not mentioned is to create a dirty URL:
/destination/param1/value1/...
then strip additional parameters at server-side and redirect:
/destination
keeping additional values stored at server-side (e.g. via sessions). I still prefer using sessionStorage in a real application, but it worth mentioning anyway.
What do you mean it will "bind content to a single url"? AJAX request is the first thing that comes to my mind as the solution to this problem. You dont have to use the url of the page to make the ajax request, you can build the url inside your javascript based on whatever conditions exist in your application.
Besides AJAX and passing parameters in the URL, the only other thing I can think of is to use Cookies. That of course runs into problems if the user has cookies disabled. I think an Ajax call to your server is the most robust way of handling the problem.

Using html5 history in place of hash urls to restore the history of the user

We have a single page application that loads results based on query string.
The query string looks like:
?city=Delhi&pn=1
The SPA has different sections on the same webpage. When user navigates to those sections, we maintain history using hash changes. For example:
?city=Delhi&pn=1#sort : Show sort parameter section of the SPA.
?city=Delhi&pn=1#filters : Show filter section of the SPA.
We are now planning to drop maintaining history using hash changes in the url and instead start using html5 history api.
How can these hash be replaces and same functionality performed using history plugin?
I tried with a + sign, for example (?city=Delhi&pn=1+sort). But looks like user cannot bookmark this and page would break since api doesn't handle + sign. + sign is taken as space in ajax api request.
What are other possibilities to handle it elegantly?
The standard means to encode the data on a query string is to add another key=value pair.
?city=Delhi&pn=1&sort=true
Note that if you are using the history API then you should have server side code capable of generating the same view that the JavaScript would generate.
e.g.
User arrives on / and gets the homepage delivered by the server
User follows a link to /?city=Delhi&pn=1&sort=true and Ajax transforms the page into another page.
User bookmarks link
User goes away
User comes back another day to their bookmark and the server (not JavaScript) builds /?city=Delhi&pn=1&sort=true
User follows another link and JS kicks in
This means that:
The site performs faster on initial load. You don't have to load the homepage and then wait for JS to make additional requests to transform it into the page you initially asked for.
It is good food for search engines
It continues to work when JS fails.

localStorage sign up users how to redirect without losing data

I have a problem with a sign up form. Every time a user creates an account I use localStorage to save the form values. But if after the submit button the user redirects to another page it saves only the last user data who signed up. If after sign up I dont redirect the user to another page I can have more than one users. What can I do to save more users (using localStorage)
the code is:
var passwords=[];
var people= [];
function submitSignUp(){
var usr = signupform.elements["username"].value;
var pass = signupform.elements["password"].value;
people.push(usr);
passwords.push(pass);
localStorage.setItem( 'peoplenames', JSON.stringify(people));
localStorage.setItem('urpasswords',JSON.stringify(passwords));
window.location.href="accountCreated.html";
}
also I use a input type button and not submit because I have the same problem with the submit input. What can I do? Thanks.
Demo
So here is the jsfiddle that should work for you.
some key things are the following.
if(localStorage.getItem('users') != null){
users = JSON.parse(localStorage.getItem('users'));
}
this code checks if the users string has been set for the current page. If users has not been set on local storage is skips this step entirely.
as for processing information from page to page, you will need to do 1 of 3 things.
Send all your calls via ajax. JQuery Get would allow you to stay on the current page while loading content from other pages. You would use the get or post like an IFrame
Navigate through your site using only get methods. Javascript wasn't meant for this, and this doesn't give you much control over the initial state of a webpage.
If you don't want to use Javascript for the rest of your life, or have personal information that shouldn't be held on a local machine. IE: passwords. Use a Server Scripting Language.
In the end it is up to you to decide what to do, but my recommendation would be to use Server Scripting Language and some sort of Database. These are web standards and are marketable skills.

how to refresh a particular part of a php page?

I have a php page which displays the result of a particular solution submitted by the user. The page is displaying an image "running" while the solution is checked in the back end and when the solution checking is finished in the back end the result is stored in the database.Now as the result got stored in the database the same php page which was displaying an image "running" should display the image and result that it got from the database. So, it needs to refresh every time to fetch the result from the database.I have used an iframe for that part of the page and passed the solution id using SESSION to the page which iframe is using and that page is fetching the data from the database. but the problem is that due to refreshing when a different solution(with different solution id) is submitted in another tab of the browser then both the previous and the current tab in the browser shows the current page since the solution id is passed using the SESSION variable. I tried Ajax also but not getting desired result. I want that a particular tab on the browser display the result of the solution which was submitted on that tab only. How can i do this please someone help.I surfed the net but dint got any desired result.
Basically, your problem is, that
you allow the same session in two different browser tabs (or windows), so the session ID is not unique between solutions
you store the solution id in the session, so the session id must be unique between solutions
You can work around your problem by removin either of these two conditions - either do not allow session re-use (bad idea IMHO) or use the solution id rather than the session id in your AJAX call for the iFrame refresh, e.g. as a GET parameter

Shall I use javascript for page submission?

I am working on a big site, and in the site there is a search module. Searching is done by using a a lot of user submitted values, so in pagination I must pass all these data to the next page, appending the values to url make the url very big.
Sso how can I solve this issue? I am planning to use a javascript based page submission (POST) with all the values in hidden fields to the next page the read all the values from the next page.
Will it cause any problems? Or should I use database to keep the search criterias?
I would create a server side object, possibly with a database backend which is updated by the different pages.
It is at my opinion the most clear and easy solution. Giving parameters from page to page, either by post or javascript or cookie will work too but it's more of a quirk in my experience.
Also if a search query is so complex that it needs multiple pages to create it, it might be helpfull for the user to have all the data stored on the server so he can change it more easily by switching back and forth between the different pages.
I would store all the search criterias in some kind of session-store on the server when the initial search is being triggered.
For pagination I would retrieve the criterias from the session-store and then just show the appropriate results. Also I would append some kind of key to the pagination links (so this would be the only hidden post-field) under which the search criterieas can be found.
Even though the session is per user, you might have several search windows open within the same session, and you don't want to mess them up with the pagination.
In order to make a reliable search with pagination, we need to do a bit more than normal.
We need to handle the following cases.
Once search is done, user may choose to do browser back and forward. Here, if you are doing form submission on every page, it would be an overload. Also, if user presses browser refresh button, it will unnecessarily warn him that data is being submitted.
Searching on a large database with lots of criteria is costly. Hence, optimization is important.
So you should NOT do the following:
Submit data on every page change
Not store data in cookie. (This is not secure and not even reliable.)
For large database with complex query, cache the result in session.
In case, you need very up-to-date and real-time result, ignore point (3) and try doing partial search for every page.
Thus, for your case, you can do the following:
When user searches first time, make the form POST data to a search page.
This search page will store the search query in session and generate a unique id for it.
Now render the result page. The result page will be passed the search id (generated in point 2) and the page number. Example result.aspx?searchId=5372947645&page=2
The result page will puck up the query from session using the searchId and then provide result based on the page number sent.
Using hidden fields and POST method should be fine too unless you are able to get them on the next page right.
To supplement Sarfraz's answer...
It's not necessary to use Javascript to make a POST.
<form action="destination_url" method="POST">
...
</form>

Categories