Check out my NEW training website for front-end web developers, FrontendMasters.com

Tutorial - CakePHP Ajax "Quick Save" with jQuery

July 15, 2008


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);

Include the 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);

Next we want to override our save function with the ajax quick save.Put this right before your $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();
}

This detects if the request is ajax, then saves the data. Then it sends back a simple, “success” message to let you know things went fine. It also writes debug to 0 and doesn’t render anything, then exits.

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);
});

This adds a button called, “Quick Save” to each form on the page where a 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.

Like this article? You'll like my NEW training website for front-end web developers!

Video workshops on jQuery, JavaScript, HTML5, web performance and more.
Upgrade your front-end developer skills!

48 comments

#1. Herus Armstrong on July 17, 2008

Good one :)

#2. Bill on September 02, 2008

Thanks for this tutorial, it’s realy usefull.
But, for work, i need to create a div with id ajax-save-message in my page, for print the success message, and i comment the Configure::write(‘debug’, 0); and set autoRender to TRUE.
With this, the message are show.

#3. Fred on October 06, 2008

Hello,

There seems to be a problem if we use the Security component.
Indeed, the use of this component, the hidden fields (hidden type) are not properly transmitted vision controller, and instead of saving it creates a new record in the table.

With the Security component, the id field of the page (or section) is transmitted like this if we use $ form→ hidden ( ‘Page.id’):
data [_Page] [id]
Note the underscore before Page.

To solve the problem temporarily, you must write the hard-hidden field, such as:

#4. Nate on November 18, 2008

Additionally, there is a problem using ajaxSubmit in relation to receiving back the response “Length Required”. It seems there’s a 411 error that’s returned sometimes. This problem can be fixed by using a GET request instead, but there are times where that doesn’t suffice (like when you have a lot of data to submit, the URL gets too long and borks).

So, as much as I’d love to use this method, it seems that until the 411 error code that gets returned is fixed either by CakePHP or by allowing us to send a Content-Length header through the JQuery request, we may be forced to use some other methodology.

Unfortunately, I don’t have a solution quite yet, but I’ve heard that .ajax() can work if you include a blank data{} variable. We’ll see.

I hope this helps someone else looking for a solution to this problem.

#5. Edmond on December 14, 2008

Hi nice piece of code!
but I have a problem implementing it.
The quick save button doesnt do anything and firebug gives the error
$(this).parents(“form:first”).ajaxSubmit isn’t a function
Any help on this?

#6. Marc Grabanski on December 14, 2008

Edmond: you probably didn’t include the jQuery form plugin.

#7. Dave Miller on January 16, 2009

Thanks Marc! Works well for me.

On the off off chance that someone is trying to use this technique with a form containing a text field that contains FCKedit (hey, you never know!) you have to tell FCKEdit to spit out it’s current contents before you submit. If your FCKedit text field model.field is, say, Post.message, then your quicksave.js would be:

jQuery(function($){
$(‘<input type=“button” value=“Quick Save” />’)
.click(function(){
FCKeditorAPI[‘Instances’][‘data[Post][message]’].UpdateLinkedField();
$(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’);
});

#8. Eduardo on February 27, 2009

When it does not goes success?

How do I make it go for the failure flow?

#9. Dave on March 31, 2009

Hi …

So, using the line below:

if ($this->RequestHandler->isAjax()) {
echo “success”
}

I assume that this will only return true if the request is via ajax request. If the user does not have JS enabled, say, you were using this on a public facing contact form etc, then would the normal action take place, and the regular view be displayed … does that make sense?

#10. Marc Grabanski on March 31, 2009

Dave, you are correct. If the request is not ajax then it will do the action it would normally, without ajax.

#11. Dave on March 31, 2009

Thanks very much, Marc. I currently learning about Cake via books etc, and have just read about the Ajax helper. The examples did not show any way to process the request if JS was not in use. The author was using:
$this→render(‘blah’, ‘ajax’);

And I was looking for a way to safe guard against no-js users/version so thanks very much.

#12. Ben on May 13, 2009

I found this post useful in getting my ajax support up and running.

Apparently $this→RequestHandler→isAjax() doesn’t work in IE7:
https://trac.cakephp.org/ticket/1935

Any recommended alternatives?

#13. Ben on May 14, 2009

Following up from my last comment…

I decided to split my action function into two: ajax and non_ajax.

#14. Julien on May 25, 2009

Thanks a LOT for this. Im using jQuery and CakePHP for a CMS. This tutorial saved me hours.

#15. Aslam Multani on August 21, 2009

Good Post…! Interesting…!

Thanks.

#16. Adnan on August 30, 2009

Thanks to @Dave Miller for his FCKeditor code.

#17. Laurent Jégou on September 25, 2009

Thanks for this very useful tutorial. The jQuery From plugin is available there : http://malsup.com/jquery/form

#18. Ron on December 28, 2009

Good stuff. Keep posting!!!

#19. 100fm6 on December 31, 2009

what I really like about the jquery is the enormous amount of developers working with it
thanks a lot

#20. IT Skill isn't enough on December 31, 2009

This is what I looking for….thanks again for the sharing…

#21. Your name on January 06, 2010

Very fine article it is.

#22. Ecommy on January 15, 2010

Interesting – I wonder however why the cake team selected prototype to be by default their ajax library

#23. jQuery on January 29, 2010

New helper with many new method implemented here: http://www.cakephp.bee.pl/

#24. nikolay on February 02, 2010

hi,

can you help me where i can find jQuery Form Plugin JavaScript, mentioned above? current link is dead…

#25. Marc Grabanski on February 02, 2010

niklay: I am sorry, here is the updated jQuery form

#26. killian on February 09, 2010

Great tutorial, I had this working at one point but it seems something in the success response text is causing cakephp to throw warning notices about missing controllers.

The ajax message goes away after the 5000ms in firefox and the form goes back to normal, however chrome just stops. I’ll see what happens when I turn the cakephp debug level down to 0. Any idea what could be happening?

#27. killian on February 09, 2010

It turns out i forgot to correctly name the form action in my view!
<?php echo $form→create(‘Article’,array(‘action’ => ‘addquick’) );
?>

#28. Ravi Panchumarthy on May 21, 2010

Thanks. Really cool plugin, much better than the inbuilt cakephp ajaxsubmit !

#29. Camilo on July 05, 2010

Nice

#30. pickatutorial.com on August 06, 2010

Good stuff!

#31. GAS Softwares on October 08, 2010

Good Post…!

Thanks.

#32. Someone on October 26, 2010

nice article!

#33. Angelica on November 12, 2010

Hello. I’ve been trying to solve the issue of FCKedit, but it has not fully functioned.

I created my editor as follows:* echo $fck→ load (‘ParametroValor’)*.

In the js function I have included the line: *FCKeditorAPI [‘ParametroValor’][‘data[parameter] [value]’].UpdateLinkedField ();
*
This value is correctly stored textArea (I’m happy about that), but the error console shows me “FCKeditorApi” is not defined, and additionally other actions that follow this instruction do not execute well.

Could guide me on what I should do?

I thank you very much.

#34. jewel on December 05, 2010

my data not save. bank row create $this→data have no data. how to solve it

#35. saddam hossain on December 09, 2010

Hello. I’ve been trying to solve the issue of FCKedit, but it has not fully functioned.

I created my editor as follows:* echo $fck? load (‘ParametroValor’)*.

In the js function I have included the line: *FCKeditorAPI [‘ParametroValor’][‘data[User] [presentaddress]’].UpdateLinkedField ();
*
This value is correctly stored textArea (I’m happy about that), but the error console shows me “FCKeditorApi” is not defined, and additionally other actions that follow this instruction do not execute well.

Could guide me on what I should do?

I thank you very much.

#36. daniel on January 25, 2011

this is frikkin awesome !

love cakephp .. coppieee !

go team people who made this thing, and also you for writing a swoit tutorial nice one brutha

#37. daniel on January 25, 2011

and your comment system is powered by leet too, shazam

I am powered by human

#38. Gavin Dotter on February 12, 2011

Took me time to read all the comments, but I really enjoyed the article.
It proved to be very helpful to me and I am sure to all the commenters
here! It’s always nice when you can not only be informed, but also
entertained!

#39. Amit on February 15, 2011

Nice tutorial….thanks for this post…..
Please visit this link for learn more script.
http://amitmondal.wordpress.com/

#40. chetan on February 16, 2011

good dear

#41. Dustin on February 19, 2011

awesome!!!

I wanted to use this all the time instead of adding a quick submit button, so I changed the code as follows, works great. Thanks for sharing

$("#YourFormName").click(function(){
$(this).ajaxSubmit({
success: function(responseText, responseCode) {
$(#ajax-save-message).hide().html(responseText).fadeIn();
setTimeout(function(){
$(#ajax-save-message).fadeOut();
}, 5000);
}
});
return false;
})
#42. Dustin on February 19, 2011

Ugh. yeah that was working but it was making the whole form a click, such a noob. Anyway, I got it to work by removing my submit button and using this code to insert the button into the submit div, and then all well!

#43. Susan on April 01, 2011

Best strategy for reporting validation errors when using this method?

#44. Leo on July 27, 2011

Hi,

everything clear, but still I am having error with the following linw
$javascript→link(array(‘jquery’, ‘form’), false);

where exactly I should put it in my view?

#45. P.A.Rochat on August 31, 2011

Great! Works for me, thanks!
I am using tinyMce in my fields. It doesn’t work for those fields if I don’t send the data back to the form before submitting. To solve the problem, just add this in the click function, before the ajax query :

tinyMCE.triggerSave();

#46. HT on September 16, 2011

I’m follow all your steps, and it’s work, but it’s just save the empty data instead the data I entered. I’m using CKeditor. Does it work with Ckeditor? What can I sold my problem? thank you

#47. HT on September 17, 2011

I sold my problem, but now, I have a question about how to update the post instead of saving it, I mean the first time we save it and after update this post?

#48. Web Development Company Faridabad on January 15, 2013

Informative Blog

Thanks for Sharing !!

Leave a comment

Comment in textile images by gravatar