Search code examples
javascriptjqueryajaxhtml5-history

HTML5 history with AJAX form


I am trying to implement HTML5 history with an AJAX form.

The form contains some radio buttons and dropdowns. Upon changing any of these inputs, the form is automatically submitted and results are returned via AJAX.

Now having implemented history, the URL gets updated, so it looks like this for example:

/currencies?type=usd&year=2015

Here is how I perform the AJAX and update the URL:

$('#currency-form input, #currency-form select').change(function() {
    var form = $('#currency-form');
    var url = form.attr('action');
    var data = form.serialize();

    $.ajax({
        url: url,
        type: 'get',
        dataType: 'json',
        data: data,
        success: function(response) {
            // update the page content
            processResponse(response.data);

            // update the page url
            window.history.pushState({}, response.meta_title, response.new_url);
        }
    });
});

To detect the back button, I have done the following:

$(window).on('popstate', function(event) {
    var state = event.originalEvent.state;

    if (state !== null) {
        console.log(state);
    }
});

There is one thing I am struggling with. Upon pressing the back button, it should pre-select the previous form values and submit the form again.

Does anybody know how I can achieve this?


Solution

  • The way to accomplish this is to push the new input field values in to state as follows:

    var state = {
        field1: $('#input1').val(),
        field2: $('#input2').val()
    };
    
    window.history.pushState(state, response.meta_title, response.new_url);
    

    Then when you detect back button event, do the following to repopulate the input fields:

    $('#input1').val(state.field1);
    $('#input2').val(state.field2);