How does AJAX work in Yii?

Here is the code from Login action of siteController.




	public function actionLogin()

	{

		$model=new LoginForm;


		// if it is ajax validation request

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

		{

			echo CActiveForm::validate($model);

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

		}

...



I don’t understand this two lines of code:


// if it is ajax validation request

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

		{

			echo CActiveForm::validate($model);

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

		}

I know how AJAX works (XMLHttpRequest object, http://www.w3schools.com/ajax/default.asp ), but in Yii I am bit lost. How do you usually use AJAX in Yii? Any tutorials available?

Thank you!

CActiveForm makes it.

AJAX-based validation: when the user enters data into an input field, an AJAX request is triggered which requires server-side validation. The validation result is sent back in AJAX response and the input field changes its appearance accordingly.

check this link CActiveForm

If you set ‘enableAjaxValidation’=>true in your CActiveForm ,everytime you interact with a form field a POST request is made to the server to validate your input.

If you look at the POST variables that your page sends to the server -with FireFox 's Firebug - you will see that one of them is called ajax and contains the id of your form.

So the snippet says : if an ajax request is being made by the form validate the form.The [font=monospace][size=2][color=#660066]CActiveForm[/color][color=#666600]::[/color][color=#000000]validate[/color]color=#666600 returns the validation result in JSON format,which contains the error messages,if any.Look at the Class Reference for validate method of CActiveForm class.[/color][/size][/font]

hello,

one other thing that’s also important to note, that Yii is not forcing you to use it’s AJAX Helper functions, you can totally write your own AJAX and use it.

actually you don’t even “have-to” use jQuery if you prefer something else. But once you learn the Yii way, of course, it’s easier that way …

–iM