When you are in an administration panel, sometimes you want a “quick save” feature that allows you to save without leaving the page.Here is how to accomplish this with CakePHP and jQuery.
To start, download jQuery and the jQuery Form Plugin JavaScript . Include them in your view with the JavaScript helper:
$javascript->link(array('jquery', 'form'), false);
RequestHandler
in your controller detect an Ajax save attempt.Also include the JavaScript helper if you haven’t already.var $helpers = array('Javascript'); var $components = array('RequestHandler');
$this->Model->save($this->data)
in your save action.if ($this->RequestHandler->isAjax()) { if ($this->Article->save($this->data)) { echo 'success'; } Configure::write('debug', 0); $this->autoRender = false; exit(); }
Lastly, lets create and include a JavaScript file that performs the quick save.
jQuery(function($){ $('<input type="button"value="Quick Save"/>') .click(function(){ $(this).parents("form:first").ajaxSubmit({ success: function(responseText, responseCode) { $('#ajax-save-message').hide().html(responseText).fadeIn(); setTimeout(function(){ $('#ajax-save-message').fadeOut(); }, 5000); } }); return false; }) .appendTo('form div.submit'); });
div
with class="submit"
exists (you may want to switch this to the id of the form you want to add quick save to). Then It also attaches a click event to the button that submits the form via the jQuery Form Plugin.In a few simple steps, we’ve created a quick save feature that saves your data whenever you want without leaving the page.