javascript - Alert message after submitting form in PHP

248

I'm using form with POST method to apply session, once the form is submitted the page reloads and I can't have any alerts on the screen.

So I've used some trick I found online but it has a problem, the alert pops up after the form submitted but none of the page design works, meaning I have only blank page and alert message.

After I click "OK' to close the alert message, the page loads.

if(empty($_SESSION["shopping_cart"])) {
    $_SESSION["shopping_cart"] = $cartArray;
    $status = "Product is added to your cart!";
    header('location:product.php?status=success');
}else{
    $array_keys = array_keys($_SESSION["shopping_cart"]);
    if(in_array($code,$array_keys)) {
        $status = "Product is already added to your cart!";
        header('location:product.php?status=failed');
    } else {
        $_SESSION["shopping_cart"] = array_merge($_SESSION["shopping_cart"],$cartArray);
        $status = "Product is added to your cart!";
        header('location:product.php?status=success');
    }

}

// This right here responsible to alert the message according to the status.
if( $_GET['status'] == 'success') {
   echo '<script>  alert("welldone");   </script>';
}
else{
   echo '<script>  alert("no good");   </script>';
}

How can I solve the page loading order so the page loads first and the alert loads second?

enter image description here

268

Answer

Solution:

After long researching, I found solution to delay the alert message with jQuerydelay() function, the delay allowing the HTML page load and then execute the alert. Thanks to all who helped me to get to this result.

  <script>
      $(document).ready(function(){
          setTimeout(function() {
              <?php
              if( $_GET['status'] == 'success') {
                  echo 'alert("welldone");';
              }
              else{
                  echo 'alert("no good");';
              }
              ?>
              }, 500);
      });
  </script>
509

Answer

Solution:

alert() stops the execution of the script and the loading of the HTML page at the point in which it was called. You should move this script to the bottom of the page.

652

Answer

Solution:

I had a lot of trouble with this one -- even using old answers marked "correct".

I found a work around. On window load and document ready didn't work. But if you add an image at the bottom of the page with the following script, it won't get called until the image is loaded (at the end of the page load).

This worked in all my testing.

<img id='workaround' src='https://picsum.photos/1/1'> <!-- any transparent 1x1 image would work -->
<script>
$("#workaround").on( "load", function(){
  alert("Image loaded.");
});
</script>

So for your purposes (or similar)

<img id='workaround' src='https://picsum.photos/1/1'>
<script>
$("#workaround").on( "load", function(){

<?php 
if( $_GET['status'] == 'success') {
   echo 'alert("welldone");';
}
else{
   echo 'alert("no good");';
}
?>
});
</script>
66

Answer

Solution:

You could defer the script tag and it won't load until after the page is rendered.

<script src="alert.js" defer></script>

Then it will load after the page renders, and there won't be a random delay (like using wait/jquery delay).

767

Answer

Solution:

Please try this code, To alert message after submitting form in PHP.

<?
if ($_POST)
    {
    if (empty($_POST['testabc'])) $msg='<script type="text/javascript">alert("BLANK");</script>';
    else $msg='<script type="text/javascript">alert("NOT BLANK");</script>';
    }
?>
<html><head></head><body>
<table>
    <tr>
        <td>
            <form id="finfo" method=POST>
                <input type="text" name="testabc">
                <input type="submit" value="info">
            </form> 
        </td>
    </tr>
</table>
<script type="text/javascript">alert("auto");</script>
<? echo $msg; ?>
</body></html>
140

Answer

Solution:

Bootstrap modal could also be a better option. Modal looks prettier than alert dialogue box. It does not change current page layout during message display.

In php code:

// This right here responsible to alert the message according to the status.
$message = '';
$show_modal = false;
if( $_GET['status'] == 'success') {
    $message = "Well Done";
    $show_modal = true;
}
else{
    $message = "No Good";
    $show_modal = true;
}

In html head tag:

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>

Then in the html:

    <div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">

            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Alert!</h4>
                </div>
                <div class="modal-body">
                    <p><?php echo ($message); ?></p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>

        </div>
    </div>

Finally show modal with condition in js:

<?php if($show_modal):?>
    <script> $('#myModal').modal('show');</script>
<?php endif;?>

People are also looking for solutions to the problem: php - how sort & display data?

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.