Movatterモバイル変換


[0]ホーム

URL:


Thursday, 23 May 2013

CakePHP and AJAX submitting a form with jQuery

A couple of years back I wrote anarticle about how to handle the dependent drop down lists problem using CakePHP's Ajax facilities. Today i will put down a trivial example of how to submit a CakePHP created form using jQuery as a small reference that can be easily pasted.

Let me remind you of the CakePHP ajax way. You start by creating a controller method that will "return" the ajax content. For our trivial example, the following controller will be more than enough.

class AjaxController extends AppController {   var $uses = NULL;   public function helloAjax()   {       $this->layout='ajax';       // result can be anything coming from $this->data       $result =  'Hello Dolly!';       $this->set("result", $result);   }}

The corresponding view fileview/ajax/hello_ajax.ctp should contain just the following:

<?php echo $result; ?>

Setting up our Ajax call is now as easy as, creating a link or a button that will invoke the asynchronous call and then setting the id of the field that will receive the result. A typical setup would be that the link looks something like this :

<a href="#">Do Ajax </a>

And then the target field can be created using:

<?php echo $this->Form->input('your_field', array('id' => 'resultField')); ?>

Finally a little script at the end of the file ...

<script>    jQuery("#performAjaxLink").click(            function()            {                                jQuery.ajax({                    type:'POST',                    async: true,                    cache: false,                    url: '<?= Router::Url(['controller' => 'ajax','admin' => FALSE, 'action' => 'helloAjax'], TRUE); ?>',                    success: function(response) {                        jQuery('#resultField').val(response);                    },                    data:jQuery('form').serialize()                });                return false;            }    );</script>

The jQuery Ajax API is availablehere.

4 comments :

Nareshsaid...

Your Ajax Code is not error Free.. Please check and Re-Post.

Athanassios Bakalidissaid...

@Naresh. You are right, thanks for the correction.

Unknownsaid...

Thank you very much i got a clue from your site now my ajax is working in which I was stuck since last 2 days

Unknownsaid...

Thanks...

Powered By Blogger