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?
Use Autocomplete
tag for the form, HTML5, but can't be sure about all browsers' compatibility.
<form action="" method="post" autocomplete="on">
See this example: Using jQuery plugin for cookies.
To set a cookie; use something like this example:
(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);
});
Then to load the values upon your desired event:
(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...
});
When submission or on live editing; try to save the entry in cookies and when you back to the form...load that values into fields.
// 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);
}
});
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);