Yii - Using Ajax Validation - ajax

I'm trying to enable ajax validation in a form, I've added the right parameters to the form, but it's not working, here's my code:
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'user-form',
'enableAjaxValidation'=>true,
'htmlOptions' => array(
'enctype' => 'multipart/form-data',
'enableClientValidation'=>true
),
)); ?>
Please advice.

In the top of your action, add the following lines:
if(isset($_POST['ajax']) && $_POST['ajax']==='user-form'){
echo CActiveForm::validate($model);
Yii::app()->end();
}

Related

Yii's default ajax is not working

In my Yii application, Yii's default Ajax is not working. Also default Ajax validation is not working. Has this been an installation problem or any other problem. How to enable Yii's default Ajax.
In my controller,
public function actionCreate() {
$model = new Company;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if (isset($_POST['Company'])) {
$company = Company::model()->findAll();
if (count($company) === 0) {
$model->attributes = $_POST['Company'];
$uploadedFile = CUploadedFile::getInstance($model, 'logo');
if (isset($uploadedFile)) {
$fileName = date('Ymdhis') . '_' . $uploadedFile->name; // $timestamp + file name
$model->logo = $fileName;
}
if ($model->validate()) {
if ($model->save()) {
if (isset($uploadedFile)) {
$uploadedFile->saveAs(Yii::app()->basePath . '/../banner/' . $fileName);
}
$this->redirect(array('create'));
}
}
} else {
Yii::app()->user->setFlash('error', 'Company details is already exists.');
}
}
$this->render('create', array(
'model' => $model,
));
}
In view page,
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'company-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
<div class="form-group">
<?php echo $form->label($model, 'company_name', array('class' => 'req')); ?>
<?php echo $form->textField($model, 'company_name', array('class' => 'form-control')); ?>
<?php echo $form->error($model, 'company_name', array('class' => 'school_val_error')); ?>
</div>
Please help me.
Thanks...
Yii has no default AJAX. This is a technology based on JavaScript language. By default Yii includes a jQuery library which provided some methods for easy manipulations with AJAX. If you want use it on your page, you should add this string:
Yii::app()->clientScript->registerCoreScript('jquery');
You can add this string to your main layout, for example into top of /views/layouts/main.php`

Ajax is not working in yii

In my Yii web application, any type of Ajax call like Ajax validation, Ajax for dependent dropdown etc.... Is not working.
My codes are,
In my form page:
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'workdetails-form',
'enableClientValidation' => true,
'clientOptions' => array(
'validateOnChange' => true,
'validateOnSubmit' => true,
),
// Please note: When you enable ajax validation, make sure the corresponding
// controller action is handling ajax validation correctly.
// There is a call to performAjaxValidation() commented in generated controller code.
// See class documentation of CActiveForm for details on this.
'enableAjaxValidation' => true,
'htmlOptions' => array('enctype' => 'multipart/form-data'),
));
?>
in controller:
public function actionCreate() {
$model = new Workdetails;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model);
if (isset($_POST['Workdetails'])) {
$model->attributes = $_POST['Workdetails'];
if ($model->validate()) {
if ($model->save()) {
$this->redirect(array('create'));
}
}
}
$this->render('create', array(
'model' => $model,
));
}
For dependant dropdown:
<div class="form-group col-sm-6">
<?php echo $form->label($model, 'designationid', array('class' => 'req')); ?>
<?php
$designation = CHtml::listData(Designation::model()->findAll(), 'designationid', 'designation_name');
echo $form->dropDownList($model, 'designationid', $designation, array(
'class' => 'form-control',
'prompt' => 'Please Select',
'ajax' => array(
'type' => 'POST',
'url' => $this->createUrl('workdetails/Fetchemployee'), // here for a specific item, there should be different URL
'update' => '#' . CHtml::activeId($model, 'employeeid'), // here for a specific item, there should be different update
'data'=>array('designationid'=>'js:this.value'),
)));
?>
<?php echo $form->error($model, 'designationid', array('class' => 'school_val_error')); ?>
</div>
How to solve this...
Please help me..
Arya I had the same problem with Yii1 and i gave up using yii-ajax validation cause i could not find a way to fix it. First make sure you have initialize/ register Yii-js file these are
yiiactiveform and yii.js
If you don't have these files on your project, it means you have not registered them. To register the core JS file proceed with this config in your main.
'clientScript' => array(
'scriptMap' => array(
'jquery.js' => true,
'jquery.min.js' => true,
),
),
or if that doesn't work use this on your main view in the header section.
Yii::app()->clientScript->registerCoreScript('jquery');
You can also add it to your base controller which is at components/Controller.php
public function init() {
parent::init();
Yii::app()->clientScript->registerCoreScript('jquery');
}
On your view have this when creating your forms. It will help in placing the error messages. to your elements
<?php
$form = $this->beginWidget('CActiveForm', array(
'id' => 'patient-registration-form',
'enableClientValidation' => True,
'enableAjaxValidation' => FALSE,
'clientOptions' => array(
'validateOnSubmit' => true,
'afterValidate' => 'js:function(form, data, hasError) {
if(hasError) {
for(var i in data) $("#"+i).parent().addClass("has-error");
return false;
}
else {
form.children().removeClass("has-error");
return true;
}
}',
'afterValidateAttribute' => 'js:function(form, attribute, data, hasError) {
if(hasError) $("#"+attribute.id).parent().addClass("has-error");
else $("#"+attribute.id).parent().removeClass("has-error");
$("#"+attribute.id).parent().addClass("has-success");
}'
),
'htmlOptions' => array(
'class' => 'form-horizontal form-bordered form-row-stripped',
),
));
?>
alternatively use Yii2 it has fixed alot of stufff and if you are loading the current page with ajax you need to render the the whole page including the js file again. since when you use renderPartial it doesn't initalize the js files hence no js scripts will work, including validation.

2 AJAX calls in the same view (CakePHP 2.3)

I have problem with AJAX in CakePHP. I have 2 different AJAX forms in one view. The first AJAX form works well, but the other one doesn't work properly. When I call the second AJAX, it doesn't set data from this form to $this->request->data, but the AJAX will run properly. After that, it will update <div id="about"></div>. Curious is fact, that after the div is updated and I try send data through this form again, it works and it will update my data in database. Also when I have only the second AJAX in the view, it will work properly and send the data first time I send the data through it.
Here's my code:
This is a view file:
<div id="price-list">
<?php echo $user['User']['price_list']; ?>
</div>
<?php
echo $this->Form->create('User');
echo $this->Form->input('User.price_list', array('label' => false));
echo $this->Js->submit('Save', array(
'url' => array('controller' => 'users', 'action' => 'ajax_edit_price_list'),
'update' => '#price-list',
'buffer' => false,
));
?>
<div id="about">
<?php echo $user['User']['about']; ?>
</div>
<?php
echo $this->Form->create('User');
echo $this->Form->input('User.about', array('label' => false));
echo $this->Js->submit('Save', array(
'url' => array('controller' => 'users', 'action' => 'ajax_edit_about'),
'update' => '#about',
'buffer' => false,
));
?>
I have also append <?php echo $this->Js->writeBuffer(); ?> in my default.ctp before </body>.
Do you have any idea, where can be a problem? Thanks
I wasn't able to reproduce your exact issue, but I think I know the problem. Your second form is being created inside of the first form. You need to add echo $this->Form->end(); to the end of both forms.
Also, the forms are getting created with the same ID. Although this isn't what's causing the problem, it's still not good. I suggest you take thaJeztah's advice and specify an ID manually inside $this->Form->create().

Yii ajax callback

I have a dependent dropdown which I fill through ajax. I want to call a function after ajax is done. How can I do this?
echo Chtml::dropDownList('optAudioSura', $strAudioSuraTemp, $suraOptions,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('QuText/audioFiles'), //url to call.
'update'=>'#optAudio',
'data'=>'js:jQuery(this).serialize()',
)
));
Thanks.
Add a success function to the ajax, e.g.:
echo Chtml::dropDownList('optAudioSura', $strAudioSuraTemp, $suraOptions,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('QuText/audioFiles'), //url to call.
'update'=>'#optAudio',
'data'=>'js:jQuery(this).serialize()',
'success'=>'function(data) {
// function code here
}',
)
));

validating form which is rendered using renderPartial in yii

I have more then one forms on one page and I am rendering one form using renderPartial, now if I want to validate it using ajax validation it don't work.
view code
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'bill-shipp-form',
'action'=>CController::createUrl('cart/index'),
'enableAjaxValidation'=>true,
'focus'=>array($billingShippingInfo,'first_name_b'),
//'enableClientValidation'=>true,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange'=>false,
'afterValidate'=>'js:postBillShipp'
),
)); ?>
and in cart/index I have
if(isset($_POST['ajax']) && $_POST['ajax']==='bill-shipp-form')
{
echo CActiveForm::validate($billingShippingInfo);
Yii::app()->end();
}
Thanks in advance
You should use 4th parameter for render partial:
$this->render('view',$data,false,TRUE);
The 4th paramater is processOutput and you should set it to true
API

Resources