HTML5 pushState using History.js. Trouble retrieving data from State.data
Asked Answered
B

1

7

I can set data into the State.data of History.js, like this:

var pushStateData = {};

function RetrieveSearchResults(type, url, searchData) {//, showResetButton, 
controlToFocus, navDirection) {

    pushStateData = {
        SearchType : type,
        SearchData : searchData,
    };

    RetrievePageResults(true, url, pushStateData);
}

function RetrievePageResults(pushNewUrl, url, pushStateData) {
    navigationInProgress = true;
    if (pushNewUrl) {
        if (window.History) {
                window.History.pushState(pushStateData, null, url);                                            
        }

        $.get(url, pushStateData.SearchData, function (reply) {
            $("#search-results").html(reply);
            navigationInProgress = false;            
        });
    }

If I set a breakpoint on the window.History.pushState statement, in Chrome, I can clearly see pushStateData has the desired values.

However, when I try to retrieve the data:

$(window).bind("statechange", function (e) {
        if (!navigationInProgress) { 
            var State = window.History.getState();

            if (window.console && window.console.log) {
                console.log("popstate", State, window.location.href);
            }

            RetrievePageResults(false, State.cleanUrl, State.data);
        }
    });

When I set a breakpoint on the RetrievePageResults statement, The State.data object no longer has any of the values I set. State.data is defined, and is not null, but it is an empty object without any apparent values.

Thanks, Scott

Buckling answered 29/2, 2012 at 17:58 Comment(0)
T
5

I don't see anything wrong with State.data, when you issue a pushState, make sure you call the History.js method:

History.pushState({state:1}, "State 1", "?state=1");

Where:

  • First Parameter => The data
  • Second Parameter => The name
  • Third Parameter => The url

It seems your not passing the state, and the data will only be present if and only if you call the History.pushState. When your visiting the URL directly (/?state=1) you would have no data in the state, data will only be available when navigating back/forward while pushing state via History.pushState.

side note: Make sure your navigationInProgress variable is fixed, you don't want it to be stalled there. Reset it when the $.get request failed when listening on the error callback. And when your pushNewUrl is false, reset the navigationInProgress attribute.

Triplenerved answered 11/8, 2012 at 23:29 Comment(2)
Thank you Mohamed, please I want to ask you, have you ever used in the third parameter of pushState a URL that contains arabic words. #16259726Centering
I have the same problem and I can manage to send only state param in data, and if I try to save anything else I can't retreive it. I think that was the questionSlot

© 2022 - 2024 — McMap. All rights reserved.