views:

285

answers:

1

Hello,

I have a problem in server side retrieving session with using ajax post request. Here is my sample code:

JavaScript:

$(function() {
    $('.jid_hidden_data').submit(function() {
        var serialized = $(this).serialize();
        var sUrl = "http://localhost/stuff";
        $.ajax({
            url: sUrl,
            type: "POST",
            data: serialized,
            success: function(data) {
                alert(data);
            }
        })
        return false;
    });
});

CodeIngiter(PHP) side:

function stuff()
{
     $post_stuff = $this->input->post('my_stuff');     // WORKS PERFECTLY
     $user_id = $this->session->userdata('user_id');   // RETURNS NULL
}

Where commented returns NULL it should return users session data, because it really exists. What is the problem? Method post doesn't get cookies or what? Thanks for any help!

Update:

For clarification i have session set with $this->session->set_userdata($data). And I don't have a problem when posting it without js/ajax. I mean with plain form submit it works fine.

+1  A: 

I had a similar problem when accessing a CI app using different domain names. Even though those domain names pointed to the same web server, I got two separate sessions.

For example, consider this Controller :

class User extends Controller
{
    function User()
    {
        parent::Controller();
        $this->load->library('session');
    }

    function login()
    {
        $this->session->set_userdata('login_token', true);
        echo 'finished logging in';
    }

    function logout()
    {
        $this->session->unset_userdata('login_token');
        echo 'finished logging out';
    }

    function status()
    {
        if ($this->session->userdata('login_token'))
        {
            echo 'logged in';
        }
        else
        {
            echo 'not logged in';
        }
    }
}

I access the following URLs in sequence. Beside each URL is the corresponding output :

http://localhost/app/user/login "finished logging in"

http://localhost/app/user/status "logged in"

http://127.0.0.1/app/user/status "not logged in"

So the session I have when accessing the app on localhost does not carry over to 127.0.0.1, even though I'm hitting the same web server.

Could it be that the domain name of the URL in your AJAX script is different to that of the URL that you are testing with?

Stephen Curran
yes, this is a problem I had. Though solved it before your answer. anyway big thanks! :)
faya