简体   繁体   中英

Displaying Message After Redirecting

What would be the best way to display a success message after submitting a form and then redirecting.

I'm developing a script with smarty template engine and i don't want to use javascript as i want it to be as easy as possible for a user to design his or her own template and i have tried using sessions to display the message it seems to unset after redirecting for example

The Form

<form action="" id="comment_form" method="POST">
    <input type="hidden" name="movie_id" id="page_id" value="{$mov.mid}" />
    <input type="hidden" name="user_id" id="user_id" value="{$logged_id}" />
    <input class="span2" name="comment" type="text" />
    <button class="btn" name="add_comment" type="submit">Add Comment</button>
</form>

PHP

if (isset($_POST['add_comment'])) {
    if (!empty($_POST['comment'])) {
        $user_id = $logged_id;
        $post_comment = mysqli_real_escape_string($con, $_POST['comment']);
        $movie->AddMovieComments($con, $movie_id,  $user_id, $post_comment);
        $_SESSION['insert'] = 'success';
        header ('Location: '.$_SERVER['REQUEST_URI']);
    } else {
        $_SESSION['insert'] = 'empty';
    }
}

Now trying to display the success in tpl

{if isset($smarty.session.insert)}
    <div class="alert alert-success">
        <button type="button" class="close" data-dismiss="alert">&times;</button>
        <h4>Success</h4>
        Your Comment was successfully added
    </div>
{/if}
{php}unset($_SESSION['insert']);{/php}

So can anyone help me out and tell me the best way to do this or tell me why it is unset before it is displayed.

Try

if( isset($_SESSION['insert']) && $_SESSION['insert'] == 'success')
{
//Your alert
unset($_SESSION['insert']);
}

I don't think a SESSION variable is the best way to do this.

In our template, have a simple condition check to see if a Smarty variable exists:

{if $success}Your comment was added{/if}

Then, in your PHP that handles the transaction, simple initiate the variable, set it to true or false depending on the outcome, and assign it in Smarty before your template is displayed

$success = false;
if (!empty($_POST['comment'])) {
    $success = true;
}
$smarty->assign("success",$success);
$smarty->display("template.tpl");

Of course, should verify that the insert was successful before you make $success = true, but you get the drift.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM