-1

I'm trying to make PHP run a function and then load a different php page using a different function. I combined the two functions into an IF statement. However the condition of the IF statement runs fine but the block (which is the header() function) does not run at all.

<?php # DISPLAY SHOPPING CART ADDITIONS PAGE.

# Access session.
session_start() ;

# Get passed product id and assign it to a variable.
if ( isset( $_GET['item_id'] ) ) $id = $_GET['item_id'] ;

# Open database connection.
require ( '..\connect_db.php' ) ;

# Retrieve selective item data from 'shop' database table.
$q = "SELECT * FROM shop WHERE item_id = $id" ;

$r = mysqli_query( $dbc, $q ) ;
if ( mysqli_num_rows( $r ) == 1 )
{
    $row = mysqli_fetch_array( $r, MYSQLI_ASSOC );

if ( isset( $_SESSION['cart'][$id] ) )
    {


        function alert($msg) {
            echo "<script type='text/javascript'>alert('$msg');</script>";
            return true; 

        }

        # Add one more of this product.
        $_SESSION['cart'][$id]['quantity']++;
        $itemName = $row["item_name"];
        alert("Another $itemName has been added to your cart");

   } 
}

# Close database connection.
mysqli_close($dbc);
# Display footer section.
include ( 'includes/footer.html' ) ;

header( "refresh:0;shop.php" );
?>

If I simply put:

$itemName = $row["item_name"];
alert("Another $itemName has been added to your cart");
added();

the added() function runs first, which is strange as I thought PHP runs sequentially. Obviously I'm doing something wrong, as I'm still studying PHP

Lothar
  • 37
  • 8
  • individually the functions work fine. Just FYI – Lothar Apr 12 '20 at 08:53
  • 5
    `alert` doesn't return a value so `if (alert(...))` will never be true. But... you can't output anything before a `header` or the header is ignored. – Nick Apr 12 '20 at 09:01
  • thanks @Nick it makes sense why the IF statement does not work – Lothar Apr 12 '20 at 09:06
  • 1
    What @Nick i think wanted to teach most was, *any* output to the page or pipe, will render `header()` useless. This will include error messages too if before `header()`. – GetSet Apr 12 '20 at 09:23
  • @GetSet indeed, you will see the dreaded ["headers already sent"](https://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) error – Nick Apr 12 '20 at 09:25

4 Answers4

0

No, the added doesn't execute first, in added you have redirect and when you redirect to another page you won't see that page yet, and you move to another page, if you remove this line: header("Location:cart.php"); You should see the result, Your code seems right.

  • yes, the added() runs first and the page goes to cart.php and I never see the popup page that I would see if the added() wasn't there. – Lothar Apr 12 '20 at 09:08
0

Yes php run code sequentially and because of this you are getting issue. In your case added() is overriding your header and your page is getting redirected to cart.php without giving alert.

Nandan Rana
  • 539
  • 3
  • 12
  • you are right but I don't understand the reason. I guess I still lack knowledge – Lothar Apr 12 '20 at 09:09
  • @Lothar : Your issue can be resolve in 3 ways. 1-> if you are using any frame work then is set_flashdata instead of how the alert. 2-> if you are not using any framework use session or browser local storage to store the message and on page load check if any message exists then display it and remove it from there. 3-> if still you want to display alert then On catch the button click event and redirect it using javascript. – Nandan Rana Apr 12 '20 at 12:47
0

You just have to add "return true;" in the alert function, so that the below condition will execute.

if (alert("Another item has been added to your cart")) { added();

}
  • Because this will insert some data before the php `header()` this will not solve the problem. As such, please delete this answer. The client will show the `alert()` apparently, but even `hello world` will break the `header()` server side. – GetSet Apr 12 '20 at 09:31
  • OP's process design is flawed. Unless you like downvotes, keep this answer here. – GetSet Apr 12 '20 at 09:38
  • by adding return true; the header now works and I'm redirected to cart.php correctly, however I don't see the popup box that I saw before. It's weird how the block is executed while the condition is not. Even if I add the alert() function before the IF statement the header works, but the popup is still not seen – Lothar Apr 12 '20 at 09:42
  • Your process "design" is wrong. You could always redirect thru javascript. But that would be a hack. Possibly you could rethink page redirection altogether. And since `alert()` can be cancelled by the user, not really a good notification strategy. – GetSet Apr 12 '20 at 09:43
  • alert can only be acknowledged. No option to cancel, that is why I thought to mix the two. I will rethink the whole thing... JS is front and PHP back.. I guess you need to know well both to make them work together... need to study more – Lothar Apr 12 '20 at 09:51
  • function alert($msg) { echo ""; return true; } – Shubham Rawat Apr 12 '20 at 09:59
  • @Lothar No, `alert()` can be "blocked" by the user altogether. But I guess it takes believing – GetSet Apr 12 '20 at 10:08
  • Thanks @ShubhamRawat I already did as per few comments above. – Lothar Apr 12 '20 at 10:10
  • Ok. I guess wisdom on *any* output before headers was lost on this whole comment thread. – GetSet Apr 12 '20 at 10:13
0

I fixed it in the following way... I added:

header( "refresh:1;cart.php" );

at the very end of the php page. Now I see the popup confirming the addition and then the page redirects after 1 second. I still don't know if the solution is standard practice but for now I'll stick to it. Many thank for your time!

Lothar
  • 37
  • 8
  • and the good thing is that it does not redirect unless user clicks OK on popup window – Lothar Apr 12 '20 at 10:15
  • to see if it redirect at all? – GetSet Apr 12 '20 at 10:26
  • It fails with The requested URL /Shop/cart2.php was not found on this server. and if I enter any other php page other than cart.php it successfully redirects there. – Lothar Apr 12 '20 at 10:32
  • Can you update your question with your updated solution? Because `echo` as your question is currently worded with source, is *before* headers. Perhaps your update would make sense of the docs on `header()`? ... Or when you do it, it just works like you want it to? I doubt you mean that. So an update on your question helps future readers. – GetSet Apr 12 '20 at 10:38