phphtmldelaypage-refresh

How can I prevent PHP delay between Javascript-echo and refresh


I have a PHP page that includes, among lots of other things, a form with an input field that, if left blank (or set to zero), results in a fatal divide by zero error in my PHP. This behavior is expected as part of my page. However, when the user submits the form with the field blank or set to zero, I added an echo for an alert box, and then an echoed refresh, with the idea being to refresh the page and avoid displaying the error message without directly suppressing errors. However, there is a delay of about a second between clicking "OK" in the alert box and the page refreshing, during which delay the error message shows.

How can I avoid this awkward delay?

Things I've tried:

Here's my code:

<html>
<body>
<form action="" method="POST" id="formid">
    <input type="submit" id="Update_record" name="Update_record" value="Update record">
    <p>Enter Density:</p>
<input name='density' type='number'></td>
        <?php

        if (isset($_POST["Update_record"])) {
            $Density = (float) $_POST["density"];

            if ($Density == 0) {
                echo '<script>
    alert("You either left density blank or put zero. This results in a divide by zero error and the record is not updated. This page will reload.)")
    </script>';
                echo "<meta http-equiv='refresh' content='1'>";
            }

            $var = 100 / $Density;
        }
        ?>
        </table>
</form>
</body>
</html>

Any ways to avoid the delay are greatly appreciated.


Solution

  • I would recommend splitting apart the concept of UI friendly error checking, from server side validation of bad data.

    On the UI, use JavaScript before you submit the form. There will be no delay doing this, and you can verify things are the way you expect them to be.

    Server side, you still have to content with malicious users attacking your forms, so do your checks there...but if there is a failure on the server side - don't get fancy. Simply refresh the existing page.

    By splitting it in two, you have the UI friendly stuff operating promptly, and you have your "catch-all" activities handled server side, without needing to inject all sorts of UI logic on the back end.