最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - destroy $_SESSION after clicking 'Cancel' button - Stack Overflow

programmeradmin1浏览0评论

I would like to destroy $_SESSION['userList'] after cliking 'Cancel' button. However, the $_SESSION['userList'] is destroied when page load.

Below is my code:

<a href='#' class="btn" onClick="resetForm()"><span>Cancel</span></a>

<script type="text/javascript">

                function resetForm() {
                    <?php

                        unset($_SESSION['userList']);

                    ?>

                }
            </script>

Really appreciate for any help.

I would like to destroy $_SESSION['userList'] after cliking 'Cancel' button. However, the $_SESSION['userList'] is destroied when page load.

Below is my code:

<a href='#' class="btn" onClick="resetForm()"><span>Cancel</span></a>

<script type="text/javascript">

                function resetForm() {
                    <?php

                        unset($_SESSION['userList']);

                    ?>

                }
            </script>

Really appreciate for any help.

Share Improve this question edited Aug 29, 2013 at 16:18 Daniel Daranas 22.6k9 gold badges65 silver badges121 bronze badges asked Mar 7, 2012 at 10:06 AcubiAcubi 2,78311 gold badges42 silver badges54 bronze badges
Add a ment  | 

6 Answers 6

Reset to default 3

You cannot execute PHP (server-side) in your javascript (client-side). You need to issue an HTTP request to invoke PHP. You can do that using AJAX.

JAVASCRIPT

$.ajax({
    type: "POST",
    url: "phppage.php",
    data: "action=unsetsession",
    success: function(msg){
        alert(msg);
        if(msg == "success"){
            //cleared session
        }else{
            //failed
        }
    },
    error: function(msg){
        alert('Error: cannot load page.');
    }
});

PHP

if($_POST['action'] == "unsetsession"){
    unset($_SESSION['userList']);
    echo "success";
}

You can not execute php code in the client side like you try in your example. If you want to to destroy session withou reload then you must use ajax request.

You better use jquery for this

<a href='#' class="btn" onClick="resetForm()"><span>Cancel</span></a>

<script>
function resetForm()
{
    jQuery.ajax({
        type: "POST",
        url: "cancel.php",
        data:,
        cache: false,
        success: function(response)
        {
        }
    });
}
</script>

And create a new cancel.php which will be like this -

<?php
unset($_SESSION['userList']);
?>

You can't call PHP from JS like this. You'll need to do a call back to the server.

Use submit button for Cancel (You can use CSS to make it look the away you want) //HTML

<form method="post" >
<input type="button" value="Cancel" name="cancel" id="cancel" />
</form>

//PHP

if(isset($_POST['cancel'))
{
  unset($_SESSION['userList']);
}
发布评论

评论列表(0)

  1. 暂无评论