5

Dealing with secuity component on my ajax calls not going as they should.

How do you deal with it in cakephp 2.x ?

Appcontroller.php

public function beforeFilter() {
        $this->Security->blackHoleCallback = 'blackhole';
        if ($this->request->is('ajax')) {
            $this->Security->validatePost = false;
        }

Does not seem to work...

Tom
  • 3,717
  • 5
  • 26
  • 28

1 Answers1

3

You can still make secure ajax calls using Cake's provided form security mechanics. To do this, render a non-visible form and place inputs to store the ajax call parameters. Then, with Javascript set these parameters in your form and do the ajax call by serializing it. Remember that if you have CSRF check enabled (and one-token-per-session is disabled) you will have to update the form with a new valid CSRF token (you can read it in the controller with $this->request->params['_Token']['key']).

Example:

<?php
    echo $this->Form->create('AjaxForm');
        echo $this->Form->hidden('value');
    echo $this->Form->end();
?>

<script>    
    function makeAjaxCall()  {
        $.post(
            ajaxUrl,
            $('#AjaxForm').serialize(),
            function(data) {
                $('#AjaxForm [name="data[_Token][key]"]').val(data.newCsrfToken)
            }
        );
    };
</script>

For further reference, we have created a component that allows to maintain security enabled on client side forms that are dinamically modified, and removes the need to unlock fields or actions when making ajax calls. You can find it at https://github.com/QTSdev/DynamicSecurity.

Tarariraz
  • 113
  • 1
  • 1
  • 7