4

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);
            });
suncoastkid
  • 2,193
  • 7
  • 26
  • 45

2 Answers2

4

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?

Community
  • 1
  • 1
suncoastkid
  • 2,193
  • 7
  • 26
  • 45
0

Try:

var postData = { csrf_token: $("input:hidden[name='csrf_token]").val() };

This basically does the same as your jquery ajax call. You might also want to get rid of the headers in $http.post().

Ye Liu
  • 8,946
  • 1
  • 38
  • 34
  • Thanks for the suggestion. That makes the post look like: {"csrf_token":"839e01fd6186fd839f5ff70f995c0f5f"} but it needs to look like: csrf_token=c30c272623b8c02b7c938d81dfb00862. I tried setting headers : {'Content-Type': 'application/x-www-form-urlencoded'} but still no joy. – suncoastkid Jun 10 '13 at 20:55
  • @user2011685 If you configure `$.ajax()` to make POST calls, the `data` is also turned into request body, not querystring. – Ye Liu Jun 10 '13 at 21:31