Skip to content

Instantly share code, notes, and snippets.

@mkurz
Created Oct 13, 2015
Embed
What would you like to do?
<!doctype html>
<title>dynamic</title>
<button onclick="addGeneratedForms()">addGeneratedForms</button>
<script>
function addGeneratedForms(){
var div = document.createElement('div');
div.innerHTML = '<form class="login" method="post" action="login">\
<input type="text" name="username">\
<input type="password" name="password">\
<button type="submit">login</button> stay on this page but update the url with pushState\
</form>';
document.body.appendChild(div);
}
document.body.addEventListener('submit', function ajax(e){
e.preventDefault();
setTimeout(function(){
// Works in chrome when the original login form does not "exist" anymore after push or ajax request
// So either remove (or hide) the form or try to change it's action url (didn't test but should work too)
// Also make sure all other forms within the same page point to a different action url
// otherwise they are considered as login form too.
e.target.parentNode.removeChild(e.target); // Or alternatively just hide the form: e.target.style.display = 'none';
history.replaceState({success:true}, 'title', "/success.html");
// This is working too!!! (uncomment the history.xxxState(..) line above) (it works when the http response is a redirect or a 200 status)
//var request = new XMLHttpRequest();
//request.open('POST', '/success.html', true); // use a real url you have instead of '/success.html'
//request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
//request.send();
}, 1);
}, false);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment