javascript - Alert message after submitting form in PHP
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?
Answer
Solution:
After long researching, I found solution to delay the alert message with jQuery
delay()
function, the delay allowing the HTML page load and then execute the alert. Thanks to all who helped me to get to this result.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.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.
So for your purposes (or similar)
Answer
Solution:
You could defer the script tag and it won't load until after the page is rendered.
Then it will load after the page renders, and there won't be a random delay (like using wait/jquery delay).
Answer
Solution:
Please try this code, To alert message after submitting form in PHP.
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:
In html head tag:
Then in the html:
Finally show modal with condition in js: