Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

180
Visualizações
How to show alerts on bad request, but redirect on success?

I have a registration form, the user is being redirected to home.php after success (works)

But also all the 'alerts/errors' which are echos in PHP, after submit, will redirect to register.php and show the error in blank white page.

(How do i display them to <div class="msg"> position?)

<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-->

register.php

Based off that, please provide a correct code snippet in order to mark this as resolved.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

It would probably make your life quite a bit easier if you always returned JSON from your PHP, rather than sometimes HTML as well.

For examples, when checking the errors at the top of register.php, you should return JSON objects --- e.g.

{error: "Email is not valid!"}

rather than their HTML equivilents.


This means that in your fetch, you'll now always be able to get the JSON content (currently, you'd probably get an error in your browser's debug console if one of those messages came back, as it's not valid JSON). Then, in your JavaScript, you can just detect this and switch however you want:

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda