Search code examples
ajaxcodeigniterangularjscsrf

Using Angular.js $http.post with Codeigniter WITH CSRF enabled


I'm trying to post via Angular.js to a CodeIgniter controller in an application that has CSRF enabled (on the same domain). With jquery, I would just add the token like so:

$.ajaxSetup({
data: {
    csrf_token: $("input:hidden[name='csrf_token']").val()
}

I've added the post values and headers in Angular.js, but no joy. Anybody know how to accomplish this?

var postData = { name:"csrf_token", value: $("input:hidden[name='csrf_token]").val() };
$http.post('myCIcontroller',postData,{headers: {'csrf_token': $("input:hidden[name='csrf_token']").val()}}).success(function(data){
                console.log(data);
            });

Solution

  • Here is a solution:

    var postData = $.param({csrf_token: $("input:hidden[name='csrf_token']").val()});
    
    $http.post('myCIcontroller', postData, {headers : {'Content-Type': 'application/x-www-form-urlencoded'}}).success(function(data){
                console.log(data);
    });
    

    More info here: How can I post data as form data instead of a request payload?