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

170
Views
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 answers
Answer question

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