Im trying to create a simple Ajax form for a message board in a CakePHP application, but I can't for the life of me figure out how to properly use the Js->submit() function to submit a form via Ajax.
Heres the form code within my view:
<?php
echo $this->Form->create('Message',array(
'type' => 'post',
'action' => 'add',
'onSubmit' => 'return false;'
));
echo $this->Form->input('name', array('label' => 'From:'));
echo $this->Form->input('text', array('label' => 'Message:'));
echo $this->Js->submit('Post Your Message', array(
'action' => 'add',
'update' => '#message_board'
));
echo $this->Form->end();
?>
<div id="message_board">
...
</div>
And here is the controller action:
function add() {
$this->autoRender = false;
if($this->RequestHandler->isAjax()) {
$this->layout = 'ajax'; //THIS LINE NEWLY ADDED
if(!empty($this->data)) {
if($this->Message->save($this->data)) {
$this->Session->setFlash('Your Message has been posted');
}
}
}
}
Oddly, what happens when I submit the form is an exact copy of the form and its containing div is duplicated INSIDE the message_board div. Weird.
Obviously I'm missing something (or several things). If anyone has any idea, or else knows a good source of information on how to use it, it would be much appreciated.
Thanks.
UPDATE: I tried adding the new line $this->layout = 'ajax';
to the controller (see above), but it had no effect. Here is the jquery output by CakePHP, incase that might tell somebody whats going on.
$(document).ready(function () {
$("#submit-707957402").bind("click", function (event) {
$.ajax({
action:"add",
data:$("#submit-707957402").closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$("#message_board").html(data);
},
type:"post",
url:"\/messages"
});
return false;
});
});