0

I cant figure out how I can use historyAPi or history.js please help! My code is like this...

What I want is a set of buttons are displayed user clicks one of them then the other set of buttons are displayed and ajax call is made in between the first set is hidden by using css...

$(".button1").click(function(){
    $('#div2').css("display","none");
    $('#div1').css("display","none");
    val1 = $(this).attr("value");
    query = 'phone.php?val1='+val1;
    myQuery();
    $('#div2').css("display","block");
});

$(".button2").click(function(){
    val2= $(this).attr("value");
    $("#div2").css("display","none");
    query = 'phone.php?val1='+val1+'&val2='+val2;
    myQuery();
   $("#div3").css("display","block");
});

function myQuery() {
    if (window.XMLHttpRequest) {
        xmlHttp = new XMLHttpRequest();
    } else {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlHttp.onreadystatechange = function(){
        if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
        document.getElementById("sql").innerHTML = xmlHttp.responseText;
    }
}

xmlHttp.open('GET', query, true);
xmlHttp.send();
}

When I press the back button it goes to the previous website ... so surely I want it to display the first set of buttons and the show the content that was there before the update.

1 Answer 1

0

When using Ajax, you do not put anything in the browser history, this is why when you press the back button, you go back to the previous recorded page. If you want your Ajax calls to be recorded like if you were going to a new page, you need to push a new state on the history stack.

if ( typeof(window.history.pushState) == 'function' ) {
    var stateObj ={
        title: title,
        url: query,
    } ;
    window.history.pushState (stateObj, title, query) ;     
}

You will also need to have a onpopstate event function implemented to hide/show your buttons based on the state becoming active after the user go back in the history.

window.onpopstate =function (event) {
    alert ("location: " + document.location + ", state: " + JSON.stringify (event.state)) ;
    // based on the event.state values, restore buttons visibility here...

} ;
2
  • so where should I exactly need to call pushState function and the onpopstate
    – Jack Cykor
    May 30, 2016 at 8:07
  • I would put it on your 'myQuery' function. you decide whether you do it only on successful query, or always based on your business logic.
    – cyrille
    May 31, 2016 at 10:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.