HTML5 story with AJAX form

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

The form contains some radio buttons and drop-down menus. After changing any of these inputs, the form is automatically submitted and the results are returned via AJAX.

Now, having implemented the story, the URL is updated, so it looks like this:

/currencies?type=usd&year=2015

This is how I execute 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 find the back button, I did the following:

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

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

There is one thing I'm struggling with. By clicking the "Back" button, he must first select the previous form values ​​and submit the form again.

Does anyone know how I can achieve this?

+4
source share
2 answers

, state :

var state = {
    field1: $('#input1').val(),
    field2: $('#input2').val()
};

window.history.pushState(state, response.meta_title, response.new_url);

, "", :

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

1- HTML5:

Autocomplete , HTML5, .

<form action="" method="post" autocomplete="on">

2- jQuery:

. : jQuery cookie.

cookie; - :

(function(){
// get elements values
var checkbox1 = $('#checkbox1').val();
var radio1 = $('input[id="radio1"]:checked').val();
var textbox1 = $("#textbox1").val()
//save elements values into cookies
$.cookie("radio1", checkbox1);  
$.cookie("checkbox1", radio1);  
$.cookie("textbox1", textbox1);  

});

:

(function (){
//read value from cookie.
var radio1= $.cookie("radio1");
var checkbox1= $.cookie("checkbox1");
var textbox1= $.cookie("textbox1");
$('#radio1').prop('checked', radio1);
$('#checkbox1').prop('checked', checkbox1);
$('#textbox1').val(textbox1);


// Etc...
}); 

; cookie, ... .

3- JSON:

:

// reset form values from json object
$.each(data, function(name, val){
    var $el = $('[name="'+name+'"]'),
        type = $el.attr('type');

    switch(type){
        case 'checkbox':
            $el.attr('checked', 'checked');
            break;
        case 'radio':
            $el.filter('[value="'+val+'"]').attr('checked', 'checked');
            break;
        default:
            $el.val(val);
    }
});
0

Source: https://habr.com/ru/post/1688151/


All Articles