'How to redirect to page with history API on popstate when submit a form with ajax?
I have an issue when using history API on form submission with Ajax, I want to automatically redirected with historyRender() when the request is successfully, but since it takes the window pop state event it does not do anything. I want function HistoryRender(url) to work work when is initialized without any click event.
How can I work it automatically with the passed URL without clicking anything on a document
//my HTML form
<form method="post" action="send.php" id="jsForm">
<input type="text" name="name" id="name">
<button type="submit">Save</button>
</form>
//my ajax
$(document).on('submit', '#jsForm', function(e){
e.preventDefault();
let $url = $(this).attr('action'),
$req;
$req = $.ajax({
url: $url,
method: 'post',
data: $(this).serialize(),
dataType: 'html',
});
$req.done((data) =>{
let $data = data;
historyRender('/url-redirect');
});
$req.fail((message, err, status)=>{
console.log("request failed" + message);
})
});
//history api
function historyRender(element = 'a', attr = 'href'){
$(document).on('click', element, function(e){
e.preventDefault();
let href = attr;
//------ user goback and forward -----------
window.onpopstate = function(e){
if(e.state)
ajaxRender(e.state.href);
};
//---------------push state
window.history.pushState({href: href}, '', href);
ajaxRender(href);
});
}
function ajaxRender(href){
let $url = href, req;
req = $.ajax({
url: $url,
method: 'GET',
cache: false,
dataType: 'html',
});
req.done((data) =>{
let $data = data,
$res = $data,
$title = $res.filter('title').text().trim();
if($data)
$('title').text($title);
($title) ? $('body').html($data) : $('body').html($data);
});
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
