How do I send form contents through Ajax?

Hello. My application has several forms and it would be very problematic for me to reload the entire page when people submit the form. What I want to do is send the form contents to the server via AJAX, have the server reply and use JavaScript to update the page (e.g. a message that says "your work is now saved").

Can I use CHtml::ajaxButton() for this? … SHOULD I use CHtml::ajaxButton() for this? I’m thinking that it might be easier to code the “save” button directly in HTML+jQuery rather than going through PHP or Yii, but if Yii has a good solution for this problem then maybe I should use it. First of all, I need to collect all the form data, put it in an object, and send it off to the server. I know how I would do this with jQuery, or with plain JavaScript, but I have no idea how I would do this with Yii.

What do you think? Should I code the "save" buttons with jQuery or should I try to use Yii for this?

Thanks for the help.

Create the form using Yii’s CHtml form functions.

Then use CHtml::ajaxSubmitButton() :) Since Yii JS is based on jQuery, don’t reinvent anything. Definitely use Yii’s capabilities.

Using Yii’s CHtml form stuff will create the form data as an object when the form is submitted, so you don’t have to do it manually.

Ok… so Yii will automatically include all of the form data in the ajax request if I only use CHtml::ajaxSubmitButton() ? That sounds fabulous. How do I access the data? In my controller I have something like this:


public function actionProfile() {

	$form = new ProfileForm;

	// Collect user profile data.

	if (isset($_POST['ProfileForm'])) {

		$form->attributes = $_POST['ProfileForm'];



	$this->renderPartial('profile', array('form' => $form));



What would I add here to access the form data? Is it somewhere inside $_POST[‘ProfileForm’]?


Yep. For example, if you passed in ‘id’, you could access it with $_POST[‘ProfileForm’][‘id’].

If you look at the source of your webpage that contains the form, you’ll see that all the form elements have a name attribute that corresponds to the array index where you can access it. This array index is the database field that your form is based on (if your using CActiveRecord).

Your form data is already stored in the $form after

$form->attributes = $_POST['ProfileForm'];

and you can access it’s records using the appropriate fields names (models’ properties names/database fields names).