I have a registration form. The register.php is checking for errors such as short password
AJAX gives an alert with the echo error from PHP.
With PHP, after an if else statement
the user will be registered and redirected successfully to Location:index.php (good)
The problem is, if there is any error, the user will be redirected to register.php
and the echo alert shows there (on white page)
AJAX
var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
if (xhr.status >= 200 && xhr.status <= 299) {
var response = JSON.parse(xhr.responseText);
if (response.location) {
window.location.href = response.location;
} else {
xhr.send(form_data);
}
}
Example 2: the alerts will display properly at <div class="msg"></div> position
(But will also throw the index.php on the msg div(same page where the alerts go)
var form = document.querySelector('.register form');
form.onsubmit = function(event) {
event.preventDefault();
var form_data = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action, true);
xhr.onload = function() {
document.querySelector('.msg').innerHTML = this.responseText;
};
xhr.send(form_data);
};
So, i want the user to be redirected to index.php & also the echo errors (register.php) to be handled by AJAX
Please understand that im new & learning, i spent a week in this.
If you choose to resolve this, please fix based off register.php and ajax code