We can attach Ajax with form helper to submit data. It work like below.
App::Helper('JavaScript')
->setAjax(Options)
->appForm(Element);
Options: These are options to configure AJAX submit. See below parameters
Parameter |
Values |
Remark |
---|---|---|
debug |
true/false |
true - Alert the response data |
autoHide |
true/false |
true - Hide Html on AJAX call complete |
messageElement |
HTML Tag Reference |
By default set .message |
loaderElement |
HTML Tag Reference |
By default set .message |
loadingImageUrl |
URL of loading Img |
By default set siteInfo.baseUrl + '/images/loading.gif' |
HTML Tag Reference: Class, Id or Name of a HTML tag in document.
After this configuration, helper works to submit a Form. Now on the basis of response we can display message, redirect or show alert. Response generates in JSON format. For example:
{"_status":"Success","_message":"Email sent successfully."}
To create JSON data we use Cryptography module and in Action Method we set Layout to "empty". See below examples:
// Display Success Message
echo App::Module("Cryptography")
->jsonEncode(
array(
"_status" => 'Success',
"_message" => 'Message sent successfully.'
)
);
// Display Error Message
echo App::Module("Cryptography")
->jsonEncode(
array(
"_status" => 'Error',
"_message" => 'Enter value correctly.'
)
);
// Redirect in new location
echo App::Module("Cryptography")
->jsonEncode(
array(
"_status" => 'Redirect',
"_location" => $this->baseUrl("/aboutus")
)
);
See an full example:
CONTROLLER:
if(!empty($this->data)){
$this->layout = 'empty';
// Display Success Message
echo App::Module("Cryptography")
->jsonEncode(
array(
"_status" => 'Success',
"_message" => 'Message sent successfully.'
)
);
}
VIEW:
<div class="message"></div>
<form method="post" id="myform" action="<?php echo $this->baseUrl("/"); ?>">
<ul>
<li>
<input type="text" name="data[Myform][field1]"
class="check_notempty" longdesc="Please enter a value" />
</li>
<li>
<input type="text" name="data[Myform][field1]"
class="check_notdefault" longdesc="Please change default value" value="My Default"/>
</li>
<li>
<input type="text" name="data[Myform][field1]"
class="check_email" longdesc="Please enter a valid email address" />
</li>
<li><input type="submit" name="data[Myform][submit]" value="Submit" /></li>
</ul>
</form>
<?php
App::Helper('JavaScript')
->setAjax(array("debug" => true, "autoHide" => true))
->appForm('#myform');
?>