Home > other >  How to show alerts on bad request, but redirect on success?
How to show alerts on bad request, but redirect on success?

Time:11-06

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

CodePudding user response:

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;
}
  • Related