Rectangle 27 5

Create a session library with your own MY_Session.php library that overwrote the sess_update method with one that only executed the update method when not an AJAX request:

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

require_once BASEPATH . '/libraries/Session.php';

class MY_Session extends CI_Session
{

    function __construct()
    {
        parent::__construct();

        $this->CI->session = $this;
    }

    function sess_update()
    {
        // Do NOT update an existing session on AJAX calls.
        if (!$this->CI->input->is_ajax_request())
            return parent::sess_update();
    }

}

You can either auto-load this library from config/autoload.php:

$autoload['libraries'] = array( 'MY_Session');

Or, you can load it later:

$this->load->library('MY_Session');

In your system/libraries/Session.php there is a function sess_update() that automatically update your last activity.This function update the session every five minutes by default.

public function sess_update()
    {
        // We only update the session every five minutes by default
        if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now)
        {
            return;
        }

        // _set_cookie() will handle this for us if we aren't using database sessions
        // by pushing all userdata to the cookie.
        $cookie_data = NULL;

        /* Changing the session ID during an AJAX call causes problems,
         * so we'll only update our last_activity
         */
        if ($this->CI->input->is_ajax_request())
        {
            $this->userdata['last_activity'] = $this->now;

            // Update the session ID and last_activity field in the DB if needed
            if ($this->sess_use_database === TRUE)
            {
                // set cookie explicitly to only have our session data
                $cookie_data = array();
                foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
                {
                    $cookie_data[$val] = $this->userdata[$val];
                }

                $this->CI->db->query($this->CI->db->update_string($this->sess_table_name,
                                            array('last_activity' => $this->userdata['last_activity']),
                                            array('session_id' => $this->userdata['session_id'])));
            }

            return $this->_set_cookie($cookie_data);
        }

        // Save the old session id so we know which record to
        // update in the database if we need it
        $old_sessid = $this->userdata['session_id'];
        $new_sessid = '';
        do
        {
            $new_sessid .= mt_rand(0, mt_getrandmax());
        }
        while (strlen($new_sessid) < 32);

        // To make the session ID even more secure we'll combine it with the user's IP
        $new_sessid .= $this->CI->input->ip_address();

        // Turn it into a hash and update the session data array
        $this->userdata['session_id'] = $new_sessid = md5(uniqid($new_sessid, TRUE));
        $this->userdata['last_activity'] = $this->now;

        // Update the session ID and last_activity field in the DB if needed
        if ($this->sess_use_database === TRUE)
        {
            // set cookie explicitly to only have our session data
            $cookie_data = array();
            foreach (array('session_id','ip_address','user_agent','last_activity') as $val)
            {
                $cookie_data[$val] = $this->userdata[$val];
            }

            $this->CI->db->query($this->CI->db->update_string($this->sess_table_name, array('last_activity' => $this->now, 'session_id' => $new_sessid), array('session_id' => $old_sessid)));
        }

        // Write the cookie
        $this->_set_cookie($cookie_data);
    }
if (!$this->CI->input->is_ajax_request())             return parent::sess_update();

yes it will work. and if you get any error please let me know.

Call to a member function is_ajax_request() on null in C:\xampp\htdocs\projects\oinvoices\system\libraries\Session.php on line 59

Checks to see if the HTTP_X_REQUESTED_WITH server header has been set, and returns boolean TRUE if it is or FALSE if not.

php - How to prevent auto logout in codeigniter? - Stack Overflow

php mysql codeigniter ion-auth
Rectangle 27 3

$ret; // declare a variable to return.
if (!$this->ion_auth->logged_in()){
    if($this->input->is_ajax_request()){
        /* This is an AJAX request, send the url back to be redirected to. */
        $ret['url'] = site_url().'auth/login';
        $ret['html'] = FALSE;
    }else{
        /* This is not ajax, it is a standard form submission, let codeigniter handle it*/
        redirect('auth/login');
    }
} else {
    if($this->input->is_ajax_request()){
        $ret['url'] = FALSE; //they are logged in, and this is ajax, don't redirect.
        $ret['html'] = $this->load->view('modal/productdetail', '', TRUE); //allow the HTML to be returned to the server
    }else{
        /* They are logged in, but this is not ajax, redirect them. */
        redirect('modal/productdetail');
    }
}    
echo json_encode($ret); //json_encode our $ret array, and send to browser

With the above, we're creating a variable called $ret that holds reference to some data when performing ajax requests. Otherwise, when not using ajax (no javascript), standard form redirection behavior ensues.

Now, in our success function, we're going to check for the existence of the data.url and data.html properties and act accordingly.

dataType: 'json', //add this so the success: knows how to parse returned data
success:function(data){
    if(data.url){
        window.location = data.url;
    }else if(data.html){
        $('element').html(data.html); // where "element" is an HTML element on your page you wish to override with a partial view
    }
}
element
$ret['html']
url
FALSE
elseif(data.html){ $('element').html(data.html); }
if(data.url){ window.location = data.url}

php - Codeigniter: Ajax Login Redirect issue with Ion Auth - Stack Ove...

php jquery ajax codeigniter ion-auth
Rectangle 27 3

$ret; // declare a variable to return.
if (!$this->ion_auth->logged_in()){
    if($this->input->is_ajax_request()){
        /* This is an AJAX request, send the url back to be redirected to. */
        $ret['url'] = site_url().'auth/login';
        $ret['html'] = FALSE;
    }else{
        /* This is not ajax, it is a standard form submission, let codeigniter handle it*/
        redirect('auth/login');
    }
} else {
    if($this->input->is_ajax_request()){
        $ret['url'] = FALSE; //they are logged in, and this is ajax, don't redirect.
        $ret['html'] = $this->load->view('modal/productdetail', '', TRUE); //allow the HTML to be returned to the server
    }else{
        /* They are logged in, but this is not ajax, redirect them. */
        redirect('modal/productdetail');
    }
}    
echo json_encode($ret); //json_encode our $ret array, and send to browser

With the above, we're creating a variable called $ret that holds reference to some data when performing ajax requests. Otherwise, when not using ajax (no javascript), standard form redirection behavior ensues.

Now, in our success function, we're going to check for the existence of the data.url and data.html properties and act accordingly.

dataType: 'json', //add this so the success: knows how to parse returned data
success:function(data){
    if(data.url){
        window.location = data.url;
    }else if(data.html){
        $('element').html(data.html); // where "element" is an HTML element on your page you wish to override with a partial view
    }
}
element
$ret['html']
url
FALSE
elseif(data.html){ $('element').html(data.html); }
if(data.url){ window.location = data.url}

php - Codeigniter: Ajax Login Redirect issue with Ion Auth - Stack Ove...

php jquery ajax codeigniter ion-auth
Rectangle 27 24

<?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 */

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.

Create a php file in /application/libraries/ with the name MY_Session (or whatever prefix you set), paste this code there and that is all. This function will override the sess_update function in the session class, checking on every request if that request was made by ajax, skipping the sess_update function.

Its a bad idea set the sess_expiration at higher values. This is a security feature that will protect you against session hijaking

PD: i'm not very fluent in english, if you dont understand something just let me know.

Warning. Use =& and not = when assigning the CI instance to a variable. Assigning by reference allows you to use the original CodeIgniter object rather than creating a copy of it. Given that sessions are used at high frequency, this is currently a memory hog.

Exactly what I'm looking for! This work like a charm, thank you!

jquery - Codeigniter session bugging out with ajax calls - Stack Overf...

jquery ajax codeigniter session cookies
Rectangle 27 2

Check your return data type. May be you can use in datatype in Ajax code. Return data can't read if condition. I am facing same problem or use this

php - In codeigniter How to redirect after login using ajax - Stack Ov...

php jquery ajax codeigniter redirect
Rectangle 27 2

Your ajax should populate your selectbox after the success response:

$.ajax({
    url: ...,
    success: function(data) {
        loadMySelectbox();
    }
});

function loadMySelectbox() {
    $.ajax({
        url: 'controller/getSelectboxData',
        success: function(data) {
            $.each(data, function(key, value) {
                $('#mySelectbox').append($('<option>').text(value.item_desc).attr('value', value.item_id));
            });
        }
    });
}

PHP

//model
function getLastRecord(){
    //select only data you really need
    $query = "select itemid, itemdesc from sale order by itemid DESC limit 1";

//controller
public function getSelectboxData() {
    $data = $this->PostModel->getLastRecord();
    $this->output->set_content_type('application/json')
         ->set_output(json_encode($data));
}

wouldn't use index as option value...it has no relationship to db fields

@FelippeDuarte , which url to be placs in loadMySelectbox function's URL attribute?? the url of VIEW where my select boxes are???

The url you select all data that you wish to use in your select box. Probably you need to create another controller method to get this data. I'll edit the answer

@FelippeDuarte , i have tried your ajax function... and i got a lil issue here... i have typed the following code ... function loadMySelectbox() { $.ajax({ url: baseurl + 'index.php/Welcome/getSelectboxData', success: function(data) { //alert('running'); $.each(data, function(index, value) { alert(value + ' ' + index); $('#opt1').append($('<option>').text(value.itemid).attr('value', value.itemid)); }); } }); }

It's not value, index. It's key, value, and your value is your object. Take a look at my answer again. Your value is your object, so you can get your values using value.item_id or value.item_desc, or whatever data you have in return.

php - Send and retrive data from database and display in select box wi...

php jquery mysql ajax codeigniter
Rectangle 27 4

Why are you encoding the response as JSON when you're not parsing JSON with your ajax?

public function checkusername($username)
{
        $this->load->model('user_model');
        $user = $this->user_model->getUser($username);
        if($user == null)
        {
            echo "notexists";
        }
        else
        {
            echo "exists";
        }  
}
$.validator.addMethod("checkUsername", 
    function(value, element) {
        var result = false;
        $.ajax({
            type:"GET",
            async: false,
            url: site_url + "/ajax/checkusername/" + value,
            success: function(msg) {
                result = (msg == "exists") ? false : true;
            }
        });
        return result;
    }, 
    "Username Already Exists."
);

@Trustos, I'm doing nearly the exact same thing with my CodeIgniter & ajax and it's working fine for me. The only difference is that mine is using type = "post". Do a console log in your ajax to see what the response looks like. Add console.log(result); as the first line inside your success callback function. Then look at your JavaScript console to see the exact value being returned.

It returns exist and notexist the values it should. Its like the error message Username already exists just keeps on popping up when it shouldn't

Thanks mate the async on false did the trick

php - Checking if user exists jquery validator,ajax and codeigneter - ...

php javascript codeigniter jquery-validate
Rectangle 27 15

The cause of the problem is a session cookie rotation when an AJAX Call is performed, the proper fix was included in CodeIgniter 3

You have four options:

Cope: I faced this problem myself before without knowing exactly the cause of it. In short, I saved the promise of each XMLHttpRequest, if the HTTP status code 401 was encountered, the client side application would request the credentials in the form of a popup, and then retry the AJAX promise.

Client side with jQuery, just add this ajaxError handler:

$(document).ajaxError(function (e, xhr, settings, exception) {
    if (xhr.status == 401)
    {
        // open your popup
        $('#login-popup').modal('open');

        // attach the xhr object to the listener
        $(document).bind( "retry-xhr", {
                xhro: xhr
            },
            function( event ) {
            // retry the xhr when fired
            $.ajax( event.data.xhro );
        });
    }
});

and when you are logged back in, just call this to retry your request:

$(document).trigger('retry-xhr');

Server side, you only need to add an if in your constructor

if (!$this->session->userdata('logged_in') && $this->input->is_ajax_request())
        {
            $this->output->set_status_header('401');
            exit;
        }

This was useful because some users would leave their web app window open overnight and the session timeout would kick in. Then the users would call me about not being able to do any AJAX function, and I would have to tell them to press F5

ps. if on Angular, I have used the HTTP Auth Interceptor Module successfully

Hack: See this post, his solution is to create another field in the ci_session table and check for both cookies, so your session will still be valid after rotation.

It also explains in detail what is causing this glitch

Upgrade: Start using the next version where it's already fixed:

if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now || $this->CI->input->is_ajax_request())

I will try that out - is there a good guide for upgrading from v2.1.4 to v3 of codeigniter? Will I need to do a lot of workarounds for my v2 app to make it v3 compatible?

It depends on what your application does, the biggest change in my opinion is that some functions now return null instead of false. If your app logic depends on that, you'll have a great time greping for those function names. I believe this is the most consise guide for upgrading: Upgrade to CI 3.00

thanks for that - i'm going to try this shortly but either way will give u the bounty for the amount of useful information you provided - thanks again :)

awesome =] be sure to try out the first option if you will have a business app running day in and out (where session timeout might become a problem)

Hi Josue - could you explain where exactly i need to add this code in my CI app? I'm just a little unsure and you seem to know the score with the issue :) thanks! :)

codeigniter - IonAuth - seems to be randomly logging me out - Stack Ov...

codeigniter session authentication codeigniter-2 ion-auth
Rectangle 27 15

The cause of the problem is a session cookie rotation when an AJAX Call is performed, the proper fix was included in CodeIgniter 3

You have four options:

Cope: I faced this problem myself before without knowing exactly the cause of it. In short, I saved the promise of each XMLHttpRequest, if the HTTP status code 401 was encountered, the client side application would request the credentials in the form of a popup, and then retry the AJAX promise.

Client side with jQuery, just add this ajaxError handler:

$(document).ajaxError(function (e, xhr, settings, exception) {
    if (xhr.status == 401)
    {
        // open your popup
        $('#login-popup').modal('open');

        // attach the xhr object to the listener
        $(document).bind( "retry-xhr", {
                xhro: xhr
            },
            function( event ) {
            // retry the xhr when fired
            $.ajax( event.data.xhro );
        });
    }
});

and when you are logged back in, just call this to retry your request:

$(document).trigger('retry-xhr');

Server side, you only need to add an if in your constructor

if (!$this->session->userdata('logged_in') && $this->input->is_ajax_request())
        {
            $this->output->set_status_header('401');
            exit;
        }

This was useful because some users would leave their web app window open overnight and the session timeout would kick in. Then the users would call me about not being able to do any AJAX function, and I would have to tell them to press F5

ps. if on Angular, I have used the HTTP Auth Interceptor Module successfully

Hack: See this post, his solution is to create another field in the ci_session table and check for both cookies, so your session will still be valid after rotation.

It also explains in detail what is causing this glitch

Upgrade: Start using the next version where it's already fixed:

if (($this->userdata['last_activity'] + $this->sess_time_to_update) >= $this->now || $this->CI->input->is_ajax_request())

I will try that out - is there a good guide for upgrading from v2.1.4 to v3 of codeigniter? Will I need to do a lot of workarounds for my v2 app to make it v3 compatible?

It depends on what your application does, the biggest change in my opinion is that some functions now return null instead of false. If your app logic depends on that, you'll have a great time greping for those function names. I believe this is the most consise guide for upgrading: Upgrade to CI 3.00

thanks for that - i'm going to try this shortly but either way will give u the bounty for the amount of useful information you provided - thanks again :)

awesome =] be sure to try out the first option if you will have a business app running day in and out (where session timeout might become a problem)

Hi Josue - could you explain where exactly i need to add this code in my CI app? I'm just a little unsure and you seem to know the score with the issue :) thanks! :)

codeigniter - IonAuth - seems to be randomly logging me out - Stack Ov...

codeigniter session authentication codeigniter-2 ion-auth
Rectangle 27 6

You can call a controller function with AJAX on your view. In this case, I'm using the jQuery library to make the call.

<script type="text/javascript">
    $.ajax({
            url: "<?=site_url("controller/function")?>",
            type: "post", // To protect sensitive data
            data: {
               ajax:true,
               variableX: "string",
               variableY: 25
               //and any other variables you want to pass via POST
                   },
            success:function(response){
            // Handle the response object
            }
        });
</script>

This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.

php - How to call codeigniter controller function from view - Stack Ov...

php codeigniter
Rectangle 27 6

You can call a controller function with AJAX on your view. In this case, I'm using the jQuery library to make the call.

<script type="text/javascript">
    $.ajax({
            url: "<?=site_url("controller/function")?>",
            type: "post", // To protect sensitive data
            data: {
               ajax:true,
               variableX: "string",
               variableY: 25
               //and any other variables you want to pass via POST
                   },
            success:function(response){
            // Handle the response object
            }
        });
</script>

This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.

php - How to call codeigniter controller function from view - Stack Ov...

php codeigniter
Rectangle 27 3

"Note: These rules can also be called as discrete functions. For example: $this->form_validation->required($string);".

php - How can I validate a ajax form in codeigniter - Stack Overflow

php forms codeigniter validation
Rectangle 27 1

My issue was with an ajax call. I was using this:

type: 'posts',

instead of

type: 'post',

php - Codeigniter $this->input->post() empty while $_POST is working c...

php codeigniter post
Rectangle 27 7

The problem here is that I'm sending the array of files instead of the single files on the AJAX call, specifically in this part of the code:

for(var i = 0; i < files.length; i++) {
    fd.append("file_" + i, files[i]);
}

The solution was to append file by file to the formData instead of the array of files, something like this:

for(var i = 0; i < files[0].length; i++) {
    fd.append("file_" + i, files[i]);
}

This will append every single file of the files array instead of the array of files itself and it solves the problem.

In conclusion I was sending the array of files instead of the single files, the clue to this was the [object FileList] that the request was showing instead of the files information, which now makes a request like this:

Content-Disposition: form-data; name="file"; filename="exfile.pdf"
Content-Type: application/pdf

javascript - CodeIgniter AJAX file upload, $_FILE is empty when upload...

javascript php jquery ajax codeigniter
Rectangle 27 8

You are probably performing ajax requests, this is a common issue...

I would suggest you to use session database and make ajax calls is to not update the session...

class MY_Session extends CI_Session {

public function sess_update()
{
    $CI =& get_instance();

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

yah i am using ajax but ,what about those page where i didn't used Ajax,which is also loging me out

php - How to prevent auto logout in codeigniter? - Stack Overflow

php mysql codeigniter ion-auth
Rectangle 27 2

If you make an Ajax form submission from the client, you'll never be able to do a browser redirect from the server. That's the difference between a regular request and an Ajax one. Either you'll need to do a regular form submission or you'll need to change the window location on the client side after the Ajax call returns.

javascript - The server immediately return to the ajax post without ex...

javascript php jquery ajax codeigniter
Rectangle 27 2

Okay haven't tested this yet but it should work.

First off don't even bother sending the data to your controller as json, just send it as a normal post request.

$.post(post_url, {'data': details}, function(data){

Then in the controller you handle the validation just like you would any form validation.

public function register(){
$this->load->library('form_validation');
$this->form_validation->set_rules($this->input->post('username'), 'Username',
'trim|required|min_length[5]|max_length[12]|xss_clean');
if($this->form_validation->run()==FALSE){
    $errors = 'Username error here';
}
//You can iterate through any other validation rules building the $errors 
//variable then pass them back to the view with:

if(isset($errors))
{
    print json_encode(array("status"=>"error", "message"=>$errors));
} else {
   /execute pass code here
}

}

After that you can echo out the errors in the view, if there are any.

It doesn't work. I don't know how the $this->validaton_form object knows to look in the $_POST array for $_POST['username']. What is with '$this->input->post['username]'' there? the code needed to be escaped to work.

That is how codeigniter handles the $_POST object. the first parameter of the validation is the thing you want to validate, the second parameter is the user friendly name you want to return to the user if there is an error and the third parameter is the things you want to check for. I also noticed there was a typo in the validation line. Try it now.

grrr, another typo. I use a custom input handler, round brackets on the $this->input->post not square.

It doesn't work. If you write var_dump($this->input->post('username')); it will return false. The code inside if brackets are executed everytime, no matter if the username is valid or not.

It's not posting to the form then. dump out the $_POST in the form to make sure the post variable is actually populating, and see edit to the if statement, lord I must have been tired when I wrote that. Sorry.

php - How can I validate a ajax form in codeigniter - Stack Overflow

php forms codeigniter validation
Rectangle 27 1

Doh! Issue is being triggered by non-fatal warnings issued from code in my model class on the php side. Codeignitor is trying to process these warnings to the screen, which is prepending them to the AJAX output, thereby bolluxing it for the json parser.

D'oh! I run into this all the time on the site I'm working on. We ended up adding a flag (debuginfo=on) so that we can turn the errors on/off. Then you can pull up the request alone in a separate tab and look at the errors. Good find!

Wouldn't it be cool if the codeigniter gods added some kind of function flag (like fname = [fname]_ajax) that made its built-in error handling for that function more AJAX compatible? Like by automatically returning it in the json_encode() output instead of pushing it to the screen? Got equivalent functionality? Please post here!!!

php - Codeigniter wrecking Ajax output? - Stack Overflow

php jquery ajax codeigniter
Rectangle 27 3

JSON.stringify(Object);

which is available in most of the latest browers, else you can use ExtJS inbuilt method

Ext.encode(Object);
JSON.parse(JSONString)
Ext.decode(JSONString)

javascript - How do I create JSON in ExtJS for an AJAX call? - Stack O...

javascript codeigniter extjs extjs3 extjs-mvc