• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

112
Views
Respuesta PHP JSON en AJAX

Tengo un formulario de registro. Quiero redirigir al usuario después de registrar correctamente (200) o mostrar errores en 400 (solicitud incorrecta)


Solo entiendo los conceptos básicos de PHP, así que si alguien se toma el tiempo para responder, corrija la sintaxis basada en esto --> register.php

¿Combinado con los siguientes ejemplos?


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

Por favor, comprenda que soy nuevo y tengo problemas para resolver esto,
una respuesta completa de php ayudaría y marcaría como resuelta

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error