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

137
Vistas
PHP AJAX redirect after register

I have a registration form. The 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 index.php (good)

header('Location:home.php');
exit;

The problem is, if there is any error, the user will be redirected to handler.php and the echo alert shows there (on white page)

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 registration form, 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 alerts to be handled by AJAX

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Regarding responding to AJAX requests with redirects, please see What is the difference between post api call and form submission with post method?. Does a better job explaining than I could.

The basic idea is that when called asynchronously, your PHP should do what it needs to do and respond with either a 200 (success) or an error status like 400 (bad request) + error details.

// make sure nothing is echo'd or otherwise sent to the
// output buffer at this stage

$errors = []; // collect errors in here

// do whatever you need to do with the $_POST / $_FILES data...

// capturing errors example...

if ($_POST['cpassword'] != $_POST['password']) {
    $errors[] = "Passwords do not match!";
}

// use content negotiation to determine response type
if ($_SERVER['HTTP_ACCEPT'] === "application/json") {
    if (count($errors)) {
        header("Content-type: application/problem+json");
        http_response_code(400);
        exit(json_encode([
            "message" => "Invalid form data or something",
            "errors" => $errors
        ]));
    }

    header("Content-type: application/json");
    exit(json_encode(["location" => "home.php"]));
}

// just a normal request, respond with redirects or HTML
// ...

foreach ($errors as $error) : ?>
    <div class="error"><?= $error ?></div>
<?php endforeach;

The client can navigate to home on success or display error information otherwise

document.querySelector(".register form").addEventListener("submit", async (e) => {
  e.preventDefault()

  const form = e.target

  const body = new FormData(form)

  // fetch is much easier to use than XHR
  const res = await fetch(form.action, {
    method: "POST",
    headers: {
      accept: "application/json", // let PHP know what type of response we want
    },
    body
  })

  const data = await res.json()

  if (res.ok) {
    location.href = data.location
  } else if (res.status === 400) {
    document.querySelector('.msg').textContent = data.message
    // also do something with data.errors maybe
  }
})
about 4 years ago · Juan Pablo Isaza Denunciar
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