Odd behaviour on performAjaxValidation()

Good morning!

I included the performAjaxValidation into my customer creation process to check if the entered email has allready bin used. This works nice in a way but the error message is only shown halve a second before the site moves on to render the view with the model id as parameter. As the customer was not saved this results in a "page not found" error.

As I understand the performAjaxValidation function the "Yii::app()->end();" should prevent this. So why is this happening?

Code:

CustomerController




	public function actionCreate()

	{

		$model=new Customer;

		$this->performAjaxValidation($model);

		

		if (isset($this->_consultant->id))

			$model->consultantId = $this->_consultant->id;

		else

			$model->consultantId = 0;


		if(isset($_POST['Customer']))

		{

			$model->attributes=$_POST['Customer'];

			if($model->save())

				//send user data to shop

				$this->createShopUser($model);

				$this->redirect(array('view','id'=>$model->id));

		}

		

		$this->render('create',array('model'=>$model));

	}






	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='customer-form')

		{

			echo CActiveForm::validate($model);

			Yii::app()->end();

		}

	}



remove the performAjaxValidation method call try this code direct in you Create action


if(isset($_POST['ajax']) && $_POST['ajax']==='customer-form')

                {

                        echo CActiveForm::validate($model);

                        Yii::app()->end();

                }

Thx for the idea but the problem remains the same. :blink:

If you are sure that $_POST[‘ajax’]===‘customer-form’ is set than it may be a client side problem. Do you use both clientSide validation AND ajaxValidation? I am really just guessing but maybe the clientSide doesn’t detect any validation error (because it can’t check the uniqueness of an email) and is therefore “allowing” a classic form submit

The head of the template looks like this:


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

	'id'=>'customer-form',

	'enableAjaxValidation'=>true,

	//'enableClientValidation'=>true,

	'focus'=>array($model,'consultantId'),

)); ?>

As I said I can see the error message for an email address already in use for halve a second before the site renders a new view (witch ends up in the 404 error). So the $_POST[‘ajax’]===‘customer-form’ work IMO.

You have an if error in your code. Look at:


if($model->save())

    //send user data to shop

    $this->createShopUser($model);

    $this->redirect(array('view','id'=>$model->id));

Even if the model isn’t saved (cause it is not valid) the user will be redirected. Use curly braces to wrap the two lines. I am pretty sure that’s the problem

Of course!

This was so obvious… but I culdn’t notice it for hours. Thx for your help!

No problem, the most obvious things are the hardest to detect. Happens to me all the time ;)