Skip to content Skip to sidebar Skip to footer

Display Alert Box Upon Form Submission

So I have these two pages: pageOne.php and pageTwo.php.The form is in pageOne.php:
....
and doing all the data collec

Solution 1:

First, a couple points:

  1. Variables (even globals) are not shared across requests like you're trying to do in your bottom example. In order for $posted to be accessible in both pages, you must persist it in some way. Usually this involves setting a session variable (e.g. $_SESSION['posted'] = true;), but it could also be persisted in a cookie, in a database, on the filesystem, in a cache, etc.

  2. Use something like if ($_SERVER['REQUEST_METHOD'] === 'POST') instead of if ($_POST). While the latter is probably safe in most cases, it's better to get in the habit of using the former because there exists an edge case where $_POST can be empty with a valid POST request, and it may be a hard bug to track down.

One potential pattern to solve your problem using the above advice:

pageOne.php:

<?php
session_start();

if (isset($_SESSION['posted']) && $_SESSION['posted']) {
    unset($_SESSION['posted']);

    // the form was posted - do something here
}
?>
...
<form>...</form>

pageTwo.php:

<?php
session_start();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $_SESSION['posted'] = true;

    // do form processing stuff here

    header('Location: pageOne.php');
    exit;
}

// show an error page here (users shouldn't ever see it, unless they're snooping around)

Solution 2:

It looks like it's a scope problem. use:

global$posted = true;

http://php.net/manual/en/language.variables.scope.php

Post a Comment for "Display Alert Box Upon Form Submission"