Skip to content

Instantly share code, notes, and snippets.

@waspinator
Last active September 25, 2015 17:03
Show Gist options
  • Save waspinator/baef5f76c88d55b26736 to your computer and use it in GitHub Desktop.
Save waspinator/baef5f76c88d55b26736 to your computer and use it in GitHub Desktop.
// UsersController.php
public function edit($id = null)
{
$user = $this->Users->get($id);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success('The user has been saved.');
} else {
$this->Flash->error('The user could not be saved. Please, try again.');
}
}
$this->set(compact('user'));
$this->set('_serialize', ['user']);
}
// Template/Users/edit.ctp
<?= $this->Form->create($user, ['id' => 'edit-form']); ?>
<?= $this->Form->input('password'); ?>
<?= $this->Form->submit(); ?>
<?= $this->Form->end() ?>
<script>
var form = $('#edit-form');
form.submit(function(e) {
var post_data = form.serializeArray();
var form_url = form.attr('action');
var form_type = 'POST';
var return_data_type = 'json';
$.ajax({
url: form_url,
data: post_data,
type: form_type,
dataType : return_data_type,
success: function(json) {
// DOM changes to show success or any validation errors and flash messsage content
},
error: function( xhr, status, errorThrown ) {
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
complete: function( xhr, status ) {
}
});
e.preventDefault();
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment