Search code examples
phpjqueryajaxcodeignitercsrf-protection

Codeigniter csrf token with ajax request (500 internal server error)


I'm having a hard time trying to make an ajax request through my CI form having the csrf token enabled. I've been doing a long research and I came up with the same solution is posted in every issue related with this one which is adding the token val to the serialized data in the ajax request. I did this in my ajaxSetup, I get the token but still experiencing the same issue.. Here is my code.

//AJAX Setup

$.ajaxSetup({

    data:{

        csrf_test_name: $("input[name='csrf_test_name']").val()
    }

 });  

//Function ajax login

$("form#login").on("submit", function(e){

    var $this = $(this);
    var mensaje = $("div.msglogin");

    $.ajax({

        type: "POST",
        url: $this.attr("action"),
        data: $this.serialize(),
        beforeSend: function() {
            mensaje.html('<p><img src="public/frontend/img/miniloader.gif"><span><small> Iniciando..</small></span></p>');
        }
    })

    .done (function(data){
        console.log($this.serialize());
            if(data == "redirect"){
                window.location.replace($("input#baselogin").val());
            }else{
                mensaje.html(data);
            }
    })

    e.preventDefault();

});

This is what I get when I console.log $this.serialize() which means the token is being send

csrf_test_name=4a4d6eb47fc8f0c8e932b3b56a4eb9c5&usuario=dan&password=meaannn

Any help will be appreciated.


Solution

  • Add the CSRF token to your data option before posting:

     $.ajax({
        type: "POST",
        url: $this.attr("action"),
        data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>',/*....your data....*/},
        beforeSend: function() {
            mensaje.html('<p><img src="public/frontend/img/miniloader.gif"><span><small> Iniciando..</small></span></p>');
        }
    })
    

    The CSRF token needs to be sent with each request so it should be specified by the data. The echo statement does this. You can add this separately and serialize, but I've shown what you are missing.