6

I am tring to use an ajax post to an action. GET requests work fine but when I try to POST I see a '400 Bad Request' in firebug and the view return a 'Black hole' response.

Here is the Jquery request:

            $.ajax({
            url:"/usermgmt/users/editUser",
            type:"POST",
            success:function(data) {
                alert('Wow this actually worked');
                //ko.applyBindings(self);

            },
            error:function() {
                alert('This will never work');
            }
        });

Is this due to the security settings of Cake or what am I missing here?

4
  • Im looking into this and I'm pretty sure its the Security component stopping me here: book.cakephp.org/2.0/en/core-libraries/components/…
    – kSeudo
    Commented May 16, 2012 at 18:19
  • Ok so if i disable the cross site security with this:$this->Security->csrfCheck = false; It works..... but obviously this is not the way to go :) Any idea?
    – kSeudo
    Commented May 16, 2012 at 18:35
  • can you post the code in /usermgmt/users/editUser
    – Leo
    Commented May 19, 2012 at 1:56
  • This was posted a few months ago, but just in case you're still looking for an answer: Are you actually trying to POST some data through the ajax request? If so, can you update the question to show what the data looks like and how you're posting it?
    – Joseph
    Commented Jun 27, 2012 at 5:59

4 Answers 4

19

Protection against form tampering is one of the basic features provided by the Security Component. As long as it is enabled, it is going to treat all POSTs as form submissions.

A regular hand-coded HTML form won't work with the Security Component enabled, so neither will a JQuery-generated POST. You can, of course, use $this->Security->validatePost = false; or $this->Security->csrfCheck = false; but then you loose the protection that the Security Component provides.

To keep the Security Component on and working as normal, you need to use the CakePHP Form Helper to create the form you're going to post via ajax. This way the data[_Token][fields] and data[_Token][unlocked] hidden fields get generated with their keys:

<?php 
    echo $this->Form->create('Test',array('id'=>'testform'));
    echo $this->Form->input('Something');
    echo $this->Form->submit();
    echo $this->Form->end();
?> 

This will generate something like this:

<form action="/your/url" id="testform" method="post" accept-charset="utf-8">
    <div style="display:none;">
        <input type="hidden" name="_method" value="POST"/>
        <input type="hidden" name="data[_Token][key]" value="9704aa0281d8b5a2fcf628e9fe6f6c8410d8f07a" id="Token937294161"/>
    </div>
    <div class="input text">
        <input name="data[Test][Something]" class="required" type="text" id="TestSomething"/>
    </div>
    <div class="submit">
        <input  type="submit" />
    </div>
    <div style="display:none;">
        <input type="hidden" name="data[_Token][fields]" value="0c81fda1883cf8f8b8ab39eb15d355eabcfee7a9%3A" id="TokenFields817327064"/>
        <input type="hidden" name="data[_Token][unlocked]" value="" id="TokenUnlocked281911782"/>
    </div>
</form>   

Now it's just a matter of serializing this form in JQuery so that it can be sent with the ajax POST:

    $('#testform').submit(function(event) {
        $.ajax({
            type: 'POST',
            url: "/your/url",
            data: $('#testform').serialize(),
            success: function(data){ 
                alert('Wow this actually worked');
            },
            error:function() {
                alert('This will never work');
            }
        });
        event.preventDefault(); // Stops form being submitted in traditional way
    });

Now if you press the submit button, the POST will succeed.

IMPORTANT: Due to the fact that the Form Helper's Tokens can only be used with the Security Component once, this solution only works if you only intend to POST once per page generation. If you need to be able to post the same form several times between page reloads then you'll need to do the following when you add the Security Component at the beginning of your Controller:

public $components = array(
    'Security' => array(
        'csrfUseOnce' => false
    )
);

...this will allow the tokens to be used for more than one request. It's not as secure but you can combine it with csrfExpires so that the tokens will expire eventually. This is all documented in the CSRF configuration section of the Cake book.

2
  • 3
    Just wanted to add to this a bit, as the error will also be found if javascript modifies a 'hidden' input field, as the token keeps track of those. If you don't want to disable the validatePost, simply change the fields from hidden to text type fields, then hide them via css (display:none). This will allow your form to be submitted properly, even if javascript changes your input fields.
    – TeckniX
    Commented Sep 12, 2012 at 18:15
  • Very good and detailed answer, this helped me out of exactly the same problem and it would have take me a while to figure out it was the SecurityComponent. +1 for you, sir!
    – Oldskool
    Commented Oct 16, 2012 at 21:56
4

FYI CakePHP 2.3 and above now includes unlockedActions just for this purpose to be used in beforeFilter in your controller, or AppController.

$this->Security->unlockedActions = array('ajaxAction');

From: http://book.cakephp.org/2.0/en/core-libraries/components/security-component.html#disabling-security-component-for-specific-actions

0

Make shure you are putting the function editUser in:

  public function beforeFilter(){
    parent::beforeFilter()
    $this->Auth->allow('editUser');
    }

inside of UsersController,

Regards

0

Joseph's answer was missing one detail for me. My form and ajax call was in index.ctp and was calling /controller/edit.ctp so my $this->Form->create call needed 'action'=>'/controller/edit' added to it.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.