0

The following is my ajax call:

  remote: 
        {
            url:"http://localhost/my_site/index_page/validate_name",
            type: "post"
        }

So in the function validate_name, I set the session cookie as follows:

$username = "test1";
$this -> session -> set_userdata('username', $username);

Now after the ajax call is completed, I check for the session data in another controller like this,

if($this -> session -> userdata('username')=='test1')

it turns out that it returns false. Why is that?

Cœur
  • 34,719
  • 24
  • 185
  • 251
Karthik
  • 365
  • 1
  • 3
  • 16

1 Answers1

1

The link posted (Codeigniter session bugging out with ajax calls) explains that:

The problem is in the sess_update function of the session class, that generates a new session_id after X seconds. Every page have a session_id, if the session_id expires before the ajax call is made, that call will fail

So the Answer consisted of a class that overrides the session features of Codeigniter, with a warning that you should avoid this. Below is the file that you must create, which allows your ajax call to be completed properly.

By agustinrc89:

<?php
/**
 * ------------------------------------------------------------------------
 * CI Session Class Extension for AJAX calls.
 * ------------------------------------------------------------------------
 *
 * ====- Save as application/libraries/MY_Session.php -====
 */

class MY_Session extends CI_Session {

    // --------------------------------------------------------------------

    /**
     * sess_update()
     *
     * Do not update an existing session on ajax or xajax calls
     *
     * @access    public
     * @return    void
     */
    public function sess_update()
    {
        $CI = get_instance();

        if ( ! $CI->input->is_ajax_request())
        {
            parent::sess_update();
        }
    }

}

// ------------------------------------------------------------------------
/* End of file MY_Session.php */
/* Location: ./application/libraries/MY_Session.php */
Cœur
  • 34,719
  • 24
  • 185
  • 251
Skewled
  • 783
  • 4
  • 12