Tengo un problema al usar la API de historial en el envío de formularios con Ajax, quiero redirigir automáticamente con historyRender() cuando la solicitud se realiza correctamente, pero dado que toma el evento de estado emergente de la ventana, no hace nada. Quiero que la función HistoryRender (url) funcione cuando se inicializa sin ningún evento de clic.
¿Cómo puedo trabajarlo automáticamente con la URL pasada sin hacer clic en nada en un documento?
//mi formulario HTML
<form method="post" action="send.php" id="jsForm"> <input type="text" name="name" id="name"> <button type="submit">Save</button> </form>//mi 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); }) });// API de historial
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); }); }