Last active
February 16, 2020 05:36
-
-
Save unders/d22dae09e9bc11c30021b68bb207a763 to your computer and use it in GitHub Desktop.
JavaScript Recipes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Try sign-in with AJAX | |
fetch('/signin', { | |
method: 'POST', | |
body: new FormData(e.target), | |
credentials: 'include' | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Get form's DOM object | |
var f = document.querySelector('#signup'); | |
f.addEventListener('submit', e => { | |
// Stop submitting form by itself | |
e.preventDefault(); | |
// Try sign-in with AJAX | |
fetch('/signin', { | |
method: 'POST', | |
body: new FormData(e.target), | |
credentials: 'include' | |
}).then(res => { | |
if (res.status == 200) { | |
return Promise.resolve(); | |
} else { | |
return Promise.reject('Sign-in failed'); | |
} | |
}).then(profile => { | |
// Instantiate PasswordCredential with the form | |
if (window.PasswordCredential) { | |
var c = new PasswordCredential(e.target); | |
return navigator.credentials.store(c); | |
} else { | |
return Promise.resolve(profile); | |
} | |
}).then(profile => { | |
// Successful sign-in | |
if (profile) { | |
updateUI(profile); | |
} | |
}).catch(error => { | |
// Sign-in failed | |
showError('Sign-in Failed'); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment