Why does this ajax form submit not work, kind of?

I have a form with "enableAjaxValidation" => true.

I submit the form to the following action …




public function actionCreate($profileFeedPostID) {

			

	$profileFeedPost = ProfileFeedPost::findOne($profileFeedPostID);

			

	$profileFeedPostComment = new ProfileFeedPostComment;

	$profileFeedPostComment->fkIDWithProfileFeedPostID = $profileFeedPost->id;

			

	if($profileFeedPostComment->load(Yii::$app->request->post())) {

				

		$profileFeedPostComment->save();

		echo "1";

								

	} else {

				

		Yii::$app->response->format = Response::FORMAT_JSON;

				

		return ActiveForm::validate($profileFeedPostComment);

				

	}

			

}



If I remove the echo "1"; the ajax validation does not work.

But if I have leave the echo "1"; in the code it does work.

I do not understand why this is happening?

With the echo "1"; removed when I submit an invalid form nothing happens at all.

With the echo "1"; in the code when I submit an invalid form it shows the error.

Why is this happening?

Hi!

How does your form setup look like?

Have you disabled client-side validation?

Also this looks strange to me:




// in "if" you fill the model with post data via "load"

if($profileFeedPostComment->load(Yii::$app->request->post())) {

	$profileFeedPostComment->save();

	echo "1";

} 

// here your model is "empty" because post data is not "filled in"

else {

	Yii::$app->response->format = Response::FORMAT_JSON;				

	return ActiveForm::validate($profileFeedPostComment);

}



Also keep in mind that there are basically 3 ways for validation:

  1. Clientside

  2. Serverside with ajax

  3. Serverside without ajax (usually in "create")

You can for example try to switch off clientside validation and build a seperate ajax validation method…

for example like:




$form = ActiveForm::begin([

	'id' => 'my-form',        

	'enableAjaxValidation' => true, // ajax validation done in controller 

	'validationUrl' => ['controller/ajax-validation'], // action which performs the ajax validation

	'enableClientValidation'=> false, // disable clientside validation       

]);



And in your controller create an ajax validation action like:




public function actionAjaxValidation(){

	$request  = Yii::$app->request; 

	$response = Yii::$app->response;


	// populate your model

	$myModel = new MyModel; 

	$myModel->load($request->post()); 


	// validate model and send ajax respone  

	$response->format = Response::FORMAT_JSON;

	return ActiveForm::validate($myModel);

}



Hope this helps you solve your problem.

Regards

Yes it helps, but I wondered why the method I was using was not working?

Hi,

Yes you are right, I needed to move the load() method above the "if" and then use validate() in the "if", all works now.

James.