Cakephp jQuery ajax form submission.
Today we are going to create an example on cakephp Jquery ajax form submission. Very beginning we will create a cakephp form using cakephp Form helper, then we will submit ajax request from view to controller, finally we will save post request data in our mysql database table.
Our mysql database table looks like
CREATE TABLE `cities` (
`id` int ( 11 ) NOT NULL ,
`name` varchar ( 100 ) NOT NULL ,
`country_id` int ( 9 ) NOT NULL ,
`created` datetime NOT NULL ,
`modified` datetime NOT NULL
) ENGINE = InnoDB DEFAULT CHARSET = utf8;
id is our primary key.
ALTER TABLE `cities`
ADD PRIMARY KEY ( `id` );
And it should be auto increment.
ALTER TABLE `cities`MODIFY`id`int (11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT = 5;COMMIT;
Here, you can see cities as a table where cities belong to a country. I have created a belongs to relation in Model /Table/CitiesTable.php
$ this->belongsTo( ‘Countries’ , [
‘foreignKey’ => ‘country_id’ ,
‘joinType’ => ‘INNER’ ,
]);
So, first I have created a method in cities controller called add, add will looks like below
public function add ()
{
$city = $this->Cities ->newEmptyEntity ();
$countries = $this->Cities->Countries->find( ‘list’ , [ ‘limit’ => 200 ]);
$this->set (compact ( ‘city’ , ‘countries’ ));
}
Here, You can see I just created a New Empty Entity for my cities table, and also fetched all countries list for city view. I Have Created AI I Add.Php File In Location Templates / Cities / Add.Php
<?= $this->Form->create($city, [ ‘id’ => ‘form’ ])>?>
<fieldset>
<legend> <? = __ ( ‘Add City’ )?> </legend>
<?php
echo $this->Form->control( ‘name’ );
echo $this->Form->control( ‘country_id’ , [ ‘options’ => $countries]);
?>
</fieldset >
<?= $this->Form->button ( __ ( ‘Submit’ ))?>
<?= $this->Form->end() ?>
Next step let’s send a post request from add.php file, you can write the below example.
<script>
$(document) .ready ( function () {
$( ‘#form’ ). submit ( function ( e ) {
e. preventDefault ();
$.ajax ({{
url: “<?= $this->Url->build([ ‘Controller’ => ‘Cities’ , ‘Action’ => ‘AddCity’ ]) ?>” ,
method: ‘POST’ ,
data: $(this).serializeArray(),
success : function (data)
{
console.log(JSON.parse(data))}
})
})
})
</script>
Here, you can see I have sent the post request in citiesController in addCity action. So, we have to create a action in cities controller like below
public function addCity ()
{
$city = $this->Cities->newEmptyEntity ();
if ($this->request->is( ‘ajax’ )) {
$error = [];
$success = [];
$city = $this->Cities->patchEntity($city, $this->request->getData());
if ($city->hasErrors())
{
$ error[ ‘validation’ ] = $city->getErrors();
}
if ($this->Cities->save($city)) {
$success[ “message” ] = “Has saved” ;
} else {
$error[ “message” ] = ‘The city could not be saved. Please, try again.’ ;
}
}
$this->set( “error” , $error);
$this->set( “success” , $success);
$this->viewBuilder()->setOption(‘serialize’ , true);
$this->RequestHandler->renderAs($this, ‘json’);
}
According to this code if there is any validation error you should get it by the getErrors () method.
Now after submitting the form you should get an alert message with a response. You can put your error message or success message anywhere you want.
Note that if you are using cakephp form helper, after creating the form you will get a hidden field for csrf If you using cakephp form helper and also serializeArray () function you will not face http 403 error. Otherwise you have to send a csrf token in http headers. That’s the topics.
Thanks all …
Written By: Alimon Karim