Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda