Tengo un formulario de registro. El PHP está buscando errores como short password
AJAX da una alerta con el error de eco de PHP.
Con PHP, después de una declaración if else,
el usuario será registrado y redirigido con éxito a index.php (bien)
header('Location:home.php'); exit; El problema es que, si hay algún error, el usuario será redirigido a handler.php y la alerta de eco se muestra allí (en la página blanca)
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); } } Ejemplo 2: las alertas se mostrarán correctamente en la posición <div class="msg"></div>
(Pero también arrojará index.php en el formulario de registro, donde van las alertas)
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); }; Entonces, quiero que el usuario sea redirigido a index.php y también que las alertas sean manejadas por AJAX
Con respecto a la respuesta a las solicitudes de AJAX con redireccionamientos, consulte ¿Cuál es la diferencia entre la llamada a la API de publicación y el envío de formulario con el método de publicación? . Hace un mejor trabajo explicando que yo.
La idea básica es que cuando se llama de forma asíncrona, su PHP debe hacer lo que debe hacer y responder con un 200 (éxito) o un estado de error como 400 (solicitud incorrecta) + detalles del error.
// 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;El cliente puede navegar a casa en caso de éxito o mostrar información de error de lo contrario
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 } })