Last active
January 18, 2020 11:02
-
-
Save aiiddqd/34ce8e582e256eb2c3c3b612b23188a0 to your computer and use it in GitHub Desktop.
Universal Ajax Form handler by vanilla JavaScript
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
FormAjax('#loginform', 'sb/v1/user/signin'); |
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
/** | |
* from https://gist.github.com/uptimizt/34ce8e582e256eb2c3c3b612b23188a0 | |
*/ | |
var FormAjax = function(elementSelector, ep, args = []){ | |
if (document.querySelector(elementSelector)) { | |
var form = document.querySelector(elementSelector); | |
} else { | |
return false; | |
} | |
var restApiEndpoint = wpApiSettings.root + ep; | |
form.addEventListener('submit', function(event) { | |
event.preventDefault(); | |
var formData = new FormData(form); | |
var submitBtnText = ''; | |
var message = ''; | |
var submitBtn = form.querySelector('input[type="submit"]'); | |
var request = new XMLHttpRequest(); | |
// submitBtn.disabled = true; | |
submitBtnText = submitBtn.value; | |
submitBtn.value = 'Подождите...'; | |
request.open("POST", restApiEndpoint); | |
request.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce); | |
request.send(formData); | |
request.onload = function() { | |
var message = ''; | |
if (request.status == 200) { // analyze HTTP status of the response | |
var response = JSON.parse(request.response); | |
if ( args.successCallback && typeof args.successCallback === 'function' ) { | |
args.successCallback(response); | |
return; | |
} | |
if(response.success){ | |
message = '<p class="success">' + response.data.message + '</p>'; | |
} { | |
message = '<div class="error_login"><p class="error">' + response.data.message + '</p></div>'; | |
} | |
// console.log(response); | |
form.querySelector('.response').innerHTML = message; | |
if (response.data.redirect) { | |
window.location.href = response.data.redirect; | |
} | |
submitBtn.disabled = false; | |
submitBtn.value = submitBtnText; | |
} else { | |
form.querySelector('.response').innerHTML = '<div class="error_login"><p class="error">' + | |
'Что-то пошло не так. Пожалуйста попробуйте еще раз.</p></div>'; | |
// Снимаем ограничение с кнопки и возврошаем прежнее зночение | |
submitBtn.disabled = false; | |
submitBtn.value = submitBtnText; | |
} | |
}; | |
request.onerror = function() { | |
submitBtn.disabled = false; | |
submitBtn.value = submitBtnText; | |
}; | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment