doushijiao0679 2015-08-20 01:02
浏览 96
已采纳

。如何在ajax中设置php会话

I have an ajax which log in but unable to set up a php session.

How is it possible to set session by php in ajax?

I already start the session in header but when this below script runs it always show me that session is true.

    <script>
$(document).ready(function() {
    var loc=true;
    var php_var;
    // process the form
    $('#loginform').submit(function(event) {

        // get the form data
        // there are many ways to get this data using jQuery (you can use the class or id also)
        var formData2 = {
            'email'              : $('input[name=email]').val(),
            'password'           : $('input[name=password]').val()
        };

        // process the form
        $.ajax({
            type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
            url         : 'http://example/api/v1/login', // the url where we want to POST
            data        : formData2, // our data object
            dataType: 'json',
            success: function(data){        
            console.log(data);      
                if(data.error){
                    //show error message here
                    $('#name-group').html('<p>'+data.message);  
                <?php $_SESSION['isloggedIn']=false;?>
                }else{

                    //handle success part       
                    $('#name-group').html('<p>Login Successful');
                    <?php $_SESSION['isloggedIn']=true;?>

                }               
              },
              error: function(jqXHR, textStatus, errorThrown){
                //request error 

                $('#name-group').html('<p>'+textStatus.message);
                console.log('jqXHR:');
                console.log(jqXHR);
                console.log('textStatus:');
                console.log(textStatus);
                console.log('errorThrown:');
                console.log(errorThrown);   
              }             
        });

        // stop the form from submitting the normal way and refreshing the page
        event.preventDefault();
    });

});
</script>

展开全部

  • 写回答

1条回答 默认 最新

  • duanlian1978 2015-08-20 01:08
    关注

    You are mixing clientside with serverside code, the php code get executed before the user get the page in the browser, so as you did it with the api, use an ajax request to a php site on your server and set there the session. Don't forget the session_start().

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

悬赏问题

  • ¥15 PADS Logic 原理图
  • ¥15 PADS Logic 图标
  • ¥15 电脑和power bi环境都是英文如何将日期层次结构转换成英文
  • ¥20 气象站点数据求取中~
  • ¥15 如何获取APP内弹出的网址链接
  • ¥15 wifi 图标不见了 不知道怎么办 上不了网 变成小地球了