[SOLVED] Ajax form submission

Can anyone give me an example of ajax form submission?

I’ve been playing around with ajaxSubmitButton unsuccessfully.

I want it to still work when javascript is disabled, in the same way the built in ajax validation falls back to server validation.

Try use ActiveForm: http://www.yiiframework.com/doc/api/CActiveForm

Follow the link, you will find an example of usage.

To send via ajax on submit form, see clientOptions property (validateOnSubmit option)

Thanks for the reply.

Yeah, I’ve been playing around with CActiveForm for a while now.

I have validateonsubmit set to true, but its ajax submission I’m trying to get working, not validation.

I have the ajaxSubmitButton working, in that I pointed it at a dummy action and got a response.

But this only works for me if the dummy action is very simple, ie one line - echo "test";

Anything else I try gives me a 500 PHP Error.

I need help writing the controller code.

I should probably mention my app is based on the blog demo and its the comment form I want to submit with ajax.

I tried basing my new action on the code in newComment but I get the errors mentioned.

Also, if I get this working, does the ajaxSubmitButton fall back to a regular submitButton if javascript is not available?

show your code controller, view and model. This is very strange behavior…

Or download lates version of framework and see in the "demos" folder example of usage (like http://www.yiiframework.com/demos/phonebook/ )


Good news! I got it working, after a fashion.

Thanks for pointing me at the phonebook demo, although the flex and web service stuff confused me, it nudged me to look for examples in other projects I’ve downloaded.

In particular this one gave me some pointers (even though it is for 1.0) -


Another thing I realized that has helped is, if you want to work out how something works, look at the source code!

Simple and obvious, but it slipped by me until recently for some reason :rolleyes:

Still not sure why I was getting 500 PHP Error before, but I think I have it cracked now.

I’m still tweaking it but Ill post my code when I’m done.

One problem I still have is it doesn’t work if javascript is disabled.

Ok I got this working, probably not the best implementation, if you have any suggestions I’m all ears.

In my post controller I have a new action -

	public function actionAjaxComment()


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


                    $comment = new Comment();


                    $error = CActiveForm::validate($comment, array('author','email','content','verifyCode'));


                        if ($post->addComment($comment)) {

                            echo 'sent';


                            echo 'fail';



                        echo $error;






ajaxComment is added to the accessRules to allow all users.

This is my view (comment\_form.php) -

<p id="update_info">&nbsp;</p>

<div id="div_com_form" class="form">

<?php $form=$this->beginWidget('CActiveForm', array(



        'clientOptions'=>array('validateOnSubmit'=>true, 'validateOnType'=>false),

)); ?>

    <p class="note">Fields with <span class="required">*</span> are required.</p>

        <div class="com_p">

            <?php echo $form->labelEx($model,'author'); ?>

            <?php echo $form->textField($model,'author',array('size'=>60,'maxlength'=>128)); ?>

            <?php echo $form->error($model,'author'); ?>


	<div class="com_p">

            <?php echo $form->labelEx($model,'email'); ?>

            <?php echo $form->textField($model,'email',array('size'=>60,'maxlength'=>128)); ?>

            <?php echo $form->error($model,'email'); ?>


	<div class="com_p">

            <?php echo $form->labelEx($model,'url'); ?>

            <?php echo $form->textField($model,'url',array('size'=>60,'maxlength'=>128)); ?>

            <?php echo $form->error($model,'url'); ?>


	<div class="com_p">

            <?php echo $form->labelEx($model,'content'); ?>

            <?php echo $form->textArea($model,'content',array('rows'=>6, 'cols'=>50)); ?>

            <?php echo $form->error($model,'content'); ?>

            <span class="hint">You may use <a href="http://daringfireball.net/projects/markdown/syntax" target="_blank">Markdown syntax</a>.</span>


        <?php if(extension_loaded('gd')&&Yii::app()->user->isGuest): ?>

        <div id="kaptcha" class="com_p">

                <?php echo $form->labelEx($model,'verifyCode'); $this->widget('CCaptcha'); 

                echo $form->textField($model,'verifyCode');

                echo $form->error($model,'verifyCode'); ?>

                <p class="hint">Please enter the letters as they are shown in the image above.

                <br/>Letters are not case-sensitive.</p>


        <?php endif; ?>

	<div id="com_sub" class="com_p">

		<?php echo  CHtml::ajaxSubmitButton(

                                $model->isNewRecord ? 'Submit' : 'Save',




                                        $("#update_info").replaceWith("<p id=\"update_info\">sending...</p>");





                                            $("#update_info").replaceWith("<p id=\"update_info\">Comment Sent</p>");

                                        }else if(data=="fail"){


                                            $("#update_info").replaceWith("<p id=\"update_info\">An error occured</p>");


                                            $("#update_info").replaceWith("<p id=\"update_info\">&nbsp;</p>");

                                            if(data.search("Comment cannot be blank.")!=-1){

                                                $("#Comment_content_em_").replaceWith("<div id=\"Comment_content_em_\" class=\"errorMessage\" style=\"\">Comment cannot be blank.</div>");


                                            if(data.search("Name cannot be blank.")!=-1){

                                                $("#Comment_author_em_").replaceWith("<div id=\"Comment_author_em_\" class=\"errorMessage\" style=\"\">Name cannot be blank.</div>");


                                            if(data.search("Email cannot be blank.")!=-1){

                                                $("#Comment_email_em_").replaceWith("<div id=\"Comment_email_em_\" class=\"errorMessage\" style=\"\">Email cannot be blank.</div>");


                                            if(data.search("Email is not a valid email address.")!=-1){

                                                $("#Comment_email_em_").replaceWith("<div id=\"Comment_email_em_\" class=\"errorMessage\" style=\"\">Email is not a valid email address.</div>");


                                            if(data.search("The verification code is incorrect.")!=-1){

                                                $("#Comment_verifyCode_em_").replaceWith("<div id=\"Comment_verifyCode_em_\" class=\"errorMessage\" style=\"\">The verification code is incorrect.</div>");





                            ); ?>


<?php $this->endWidget(); ?>


As you can see it’s a bit messy, and not exactly reusable, but it does work.

Most things I try in Yii I find incredibly simple and quick, once I understand whats going on, not this one.

With javascript disabled the submit button appears to do nothing, any ideas how to fix that?

Also as a result of my fiddlings comment update in the backend is broken, but I haven’t looked into that yet, I might just change it to use the old form.

According to your code, if javascript not available, action render to screen "sent" (if comment add successfully).

If you want another acion, try smth like this:


	//... you code...






And in view render this flash…

ajaxButton… to work this, add in $htmlOptions: ‘type’=>‘submit’

Excellent, many thanks Nagash, it works :)

Learning all the time…


Still no native answer to this problem?


A working example of ajax form submission in Yii framework.