Making a jquery ajax call with Security component activated in CakePHP 2

Making a jquery ajax call with Security component activated in CakePHP 2

This topic sure took me a while to figure out. None of my ajax jquery posts was going trough when security component was activated, but GET did work.

So here is how you do it:

– Use Cake Libs 2.3 or later.

Ajax call:

<?php
$this->Html->scriptBlock("
$('.DomyAjaxcall').click(function(e){
  $.ajax({
    type: "post",
    url: "/controller/action",
    data: {"id" : id},
    dataType: "json"
  });
});
", array('block' => 'scriptBottom'));

echo $this->Html->link('Doajax', array('class'=>'DomyAjaxcall'));

// you should put this in your layout.ctp bottom before </body>
echo $this->fetch('scriptBottom'); 
?>

Yourcontroller.php

public $components = array('Security','RequestHandler');

        public function beforeFilter() {
            parent::beforeFilter();
            $this->Security->unlockedActions = array('ajax_action');
        }

public function ajax_action() {
        $this->autoRender = false;
            if ($this->request->is('ajax')) {
                echo 'Working';
            }
        return;
    }

 

We are telling cake libs to unlock the action for security component to allow for ajax calls as you usually post them multiple times. Security compoents hidden token fields are not updated on every call, and it will not alow you to manually change hidden fields from jquery/java using ajax, but will “BLACKHOLE” you and break your functionality.

Have Fun!

Category: CakePHP 2.x Tags: , , ,

You might also like:

  • Pingback: Jquery twitter bootstrap typeahead ajax user search with onselect in CakePHP 2 | WhatsWhat.no()

  • sting

    I appreciate your work,

    could you please tell me that where to put this Ajax call, I am totally noob to cake also I want to know that how to do “live search in cakephp”.
    thatnks

    • http://energitilskudd.no/ Tom-Erik Johannessen

      you can put it in your view.ctp file, or in a separate myscript.js file. I updated the tutorial with some php cake methods to do it. Use firebug in FF to check out what is happening. goood luck!

  • http://twitter.com/MikeFerak Michal Ferák

    Thanks, you saved me a ton of time and lots of headaches!

  • Pingback: A complete RESTful service and client in CakePHP tutorial - Mifty is Bored()

  • vipul rajvanshi

    public function ajax_action() {
    $this->autoRender = false;
    if ($this->request->is(‘ajax’)) {
    echo ‘Working';
    }
    return;
    }

    I want to show an alert on ctp file, once ajax request is black hold.
    What code I need to replace with ” echo ‘Working';”?
    Please suggest