[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/ )

Yes

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

http://code.google.com/p/yii-skeleton-app/

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'])){

                    $post=$this->loadModel();

                    $comment = new Comment();

                    $comment->setAttributes($_POST['Comment']);

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

                    if($error=='[]'){

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

                            echo 'sent';

                        }else{

                            echo 'fail';

                        }

                    }else{

                        echo $error;

                    }

                }else{

                    $this->redirect(array("site/index"));

                }

	}

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(

	'id'=>'comment-form',

	'enableAjaxValidation'=>true,

        '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>

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

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

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

        </div>

        <?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>

        </div>

        <?php endif; ?>

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

		<?php echo  CHtml::ajaxSubmitButton(

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

                                CHtml::normalizeUrl(array('post/ajaxComment','id'=>$post->id)),

                                array(

                                    'beforeSend'=>'function(){

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

                                    }',

                                    'success'=>'function(data){

                                        if(data=="sent"){

                                            $("#div_com_form").hide();

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

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

                                            $("#div_com_form").hide();

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

                                        }else{

                                            $("#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>");

                                            }

                                        }

                                    }',

                                )

                            ); ?>

	</div>

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

</div>

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:


	if(Yii::app()->request->isAjaxRequest){

	//... you code...

	}

	else{

		Yii::app()->user->setFlash(...);

		$this->redirect(...);

	}

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…

Hi!

Still no native answer to this problem?

thx

A working example of ajax form submission in Yii framework.

http://www.yiiframework.com/wiki/388/ajax-form-submiting-in-yii/