Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

168
Views
¿Cómo mostrar alertas en una solicitud incorrecta, pero redirigir en caso de éxito?

Tengo un formulario de registro, el usuario está siendo redirigido a home.php después del éxito (funciona)

Pero también todas las 'alertas/errores' que son ecos en PHP, después de enviar, se redirigirán a register.php y mostrarán el error en una página en blanco.

(¿Cómo los muestro en la posición <div class="msg"> ?)

 <script> 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 } }) </script> <body> <div class="msg"></div> <!--position for error/ wrong pass etc-->

registro.php

En base a eso, proporcione un fragmento de código correcto para marcar esto como resuelto.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Probablemente haría su vida un poco más fácil si siempre devolviera JSON desde su PHP, en lugar de HTML a veces también.

Por ejemplo, al verificar los errores en la parte superior de register.php , debe devolver objetos JSON --- por ejemplo

 {error: "Email is not valid!"}

en lugar de sus equivalentes HTML.


Esto significa que en su fetch , ahora siempre podrá obtener el contenido JSON (actualmente, probablemente reciba un error en la consola de depuración de su navegador si uno de esos mensajes regresa, ya que no es un JSON válido). Luego, en su JavaScript, puede detectar esto y cambiar como quiera:

 if (data.error) { // If there is an error document.querySelector(".msg").textContent = data.error; } else if (data.location) { // If we want to redirect the user somewhere window.location.href = "./" + data.location; }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!