doushijiao0679 2015-08-20 09: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 09: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 I350 Gigabit Network
    • ¥15 关于#abap#的问题,请各位专家解答!
    • ¥20 内网通过公网访问外网问题
    • ¥20 谁有这个东西 继续教育的
    • ¥15 怎么使请求通过cors
    • ¥15 WDM 驱动ACPI 相关疑问
    • ¥15 prism 跨窗体共享数据绑定 wpf
    • ¥15 hdl designer突然用不了系统的moduleware组件,请问有人遇到或者怎么解决吗?
    • ¥15 0基础计算机毕设,应该从哪开始?
    • ¥60 使用DKT40脑图划分ROI区域