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);
            });

2 Answers 2

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?

Sign up to request clarification or add additional context in comments.

Comments

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().

2 Comments

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.
@user2011685 If you configure $.ajax() to make POST calls, the data is also turned into request body, not querystring.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.