user1958458
user1958458

Reputation: 37

pass value from jquery to Cakephp controller

I am beginner to CakePHP and trying the send the textbox value during change function to my controller action using ajax.

Can someone help to how to pass the value form jquery to cakephp controller. If there is example code could great.

Upvotes: 0

Views: 1622

Answers (1)

david.philip
david.philip

Reputation: 430

Let's say you want to send your data to a method called 'ajax_process' in the users controller. Here's how I do it:

in your view .ctp (anywhere)

<?php
echo $this->Form->textarea('text_box',array(
    'id' => 'my_text',
));
?>
<div id="ajax_output"></div>

In the same view file - the jquery function to call on an event trigger:

function process_ajax(){
        var post_url = '<?php echo $this->Html->url(array('controller' => 'users', 'action' => 'ajax_process')); ?>';

        var text_box_value = $('#my_text').val();

        $.ajax({
            type : 'POST',
            url : post_url,
            data: {
                text : text_box_value
            },
            dataType : 'html',
            async: true,
            beforeSend:function(){
                $('#ajax_output').html('sending');
            },
            success : function(data){
                $('#ajax_output').html(data);
            },
            error : function() {
                $('#ajax_output').html('<p class="error">Ajax error</p>');
            }
        });
    }

In the UsersController.php

public function ajax_process(){
    $this->autoRender = false; //as not to render the layout and view - you dont have to do this
    $data = $this->request->data; //the posted data will come as $data['text']
    pr($data); //Debugging - print to see the data - this value will be sent back as html to <div id="ajax_output"></div>
}

Disable cake's security for the ajax_process method, in AppController.php:

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

I haven't tested any of this code but it should give you what you need

Upvotes: 1

Related Questions