Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

262
Views
PHP Redirect and Ajax

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)

register.php

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!