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

148
Vistas
PHP JSON response in AJAX

I have a registration form. I want to redirect the user after register success (200) or display errors on 400 (bad request)


I only understand basics of PHP so if anyone takes time to answer, please fix the syntax based off this --> register.php

Combined with the examples below?


// 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
  }
})

Please understand that im new and i have trouble resolving this,
a complete php answer would help & mark as resolved

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