Created
October 19, 2022 07:22
-
-
Save nerkat/f6117c2f8ed302a59ed7295add3b81f9 to your computer and use it in GitHub Desktop.
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
var isLogin; | |
var submitButton; | |
document.forms['customer_login'].addEventListener('submit', (event) => { | |
// show loading gif on submit button | |
submitButton = event.target.querySelector('button'); | |
submitButton.classList.add('spin'); | |
submitButton.disabled = true; | |
// prevent form submit | |
event.preventDefault(); | |
// boolean flag - form is for login/register | |
isFormLogin = event.target.action.includes('account/login')?true:false; | |
// fetch call to get answer from shopify | |
fetch(event.target.action, { | |
method: 'POST', | |
body: new URLSearchParams(new FormData(event.target)) | |
}) | |
.then((response) => { | |
// boolean flag - redicrect url is login/account (login/register success) | |
isLogin = response.url.includes('account/login'); | |
// return response THML body | |
return response.text(); | |
}) | |
.then(body => { | |
// hide loading gif on submit button | |
submitButton.classList.remove('spin'); | |
submitButton.disabled = false; | |
if(isFormLogin){ | |
if(!isLogin){ | |
// go to redirect | |
window.location.href = 'account'; | |
} | |
else{ | |
// show error on page | |
document.querySelector('#formErrorsSpan').innerHTML = 'Login Failed'; | |
} | |
} | |
else{ | |
// create elemnt to parse the response body to HTML and get the DOM element holding the errors | |
var el = document.createElement( 'html' ); | |
el.innerHTML = body; | |
let errors = el.getElementsByClassName("errors")[0]; | |
if(errors){ | |
// if exist - map to string array | |
errors = Array.from(el.getElementsByClassName("errors")[0].getElementsByTagName("UL")[0].getElementsByTagName("li")).map(li=>{ | |
return li.innerHTML; | |
}); | |
// show errors on page - with line-break between them if multiple | |
document.querySelector('#formErrorsSpan').innerHTML = errors.join('<br>'); | |
} | |
else{ | |
// go to redirect | |
window.location.href = 'account'; | |
} | |
} | |
}) | |
.catch((error) => { | |
console.log('error: ' + error); | |
// TODO handle error | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment