You are viewing revision #4 of this wiki article.
This version may not be up to date with the latest version.
You may want to view the differences to the latest version or see the changes made in this revision.
hi guys, Here I'm going to give you a working example of ajax form submiting in Yii.
You can try a simple demo here:DEMO
Find the source code @https://github.com/sirinibin/yiidemos
PersonForm model ¶
<?php
class PersonForm extends CFormModel
{
public $name;
public $age;
/**
* Declares the validation rules.
* title is required
*/
public function rules()
{
return array(
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels()
{
return array(
'name'=>'Name',
'age'=>'Age',
);
}
}
?>
form:
person_form.php ¶
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'person-form-edit_person-form',
'enableAjaxValidation'=>false,
'htmlOptions'=>array(
'onsubmit'=>"return false;",/* Disable normal form submit */
'onkeypress'=>" if(event.keyCode == 13){ send(); } " /* Do ajax call when user presses enter key */
),
)); ?>
<?php echo $form->errorSummary($model); ?>
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->textField($model,'name'); ?>
<?php echo $form->error($model,'name'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'age'); ?>
<?php echo $form->textField($model,'age'); ?>
<?php echo $form->error($model,'age'); ?>
</div>
<div class="row buttons">
<?php echo CHtml::Button('SUBMIT',array('onclick'=>'send();')); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
<script type="text/javascript">
function send()
{
var data=$("#person-form-edit_person-form").serialize();
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("person/ajax"); ?>',
data:data,
success:function(data){
alert(data);
},
error: function(data) { // if error occured
alert("Error occured.please try again");
alert(data);
},
dataType:'html'
});
}
</script>
Controller:
PersonController.php ¶
class PersonController extends CController
{
public function actionAjax()
{
$model=new PersonForm;
// uncomment the following code to enable ajax-based validation
/*
if(isset($_POST['ajax']) && $_POST['ajax']==='person-form-edit_person-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
*/
if(isset($_POST['PersonForm']))
{
$model->attributes=$_POST['PersonForm'];
if($model->validate())
{
// form inputs are valid, do something here
print_r($_REQUEST);
return;
}
}
$this->render('person_form',array('model'=>$model));
}
In the above example you will get an alert on the javascript ajax callback function which will be a server response from the controller action.You can customise this code as per your needs.i hope this will help someone.Thanks
-Sirin Hire Yii developer
Nice one
I have been struggling with this you just saved my time.
Thanks bonnie
Thanks bonnie
sirin k
Hi, is bonnie again I need to use this in my yii app. Can you show example of submitting data to the login controller then redirect the user to profile or any page. Thanks.
Hi bonnie
hey bonnie.if you need to achive that usign this ajax form means you can simply use the below js code in your ajax response or success section.
success:function(data){ window.location="<?php echo Yii::app()->createAbsoluteUrl("controller/action");?>"; },
Thanks
Will give it a try.
Alternative method
I was trying to figure out if there was an actual Yii-specific way of doing an AJAX submit, but there doesn't seem to be any via the
CActiveForm.clientOptions
property. The closest AJAX'y thing I could find deals only with validation (and not submission). Though, I did find this tidbit inCActiveForm.clientOptions
In your
CActiveForm
options, set theclientOptions
array to the following:array( 'clientOptions'=>array( 'validateOnSubmit'=>true, // Required to perform AJAX validation on form submit 'afterValidate'=>'js:mySubmitFormFunction', // Your JS function to submit form ), ),
Go ahead and setup your Javascript function
[javascript] function mySubmitFormFunction(form, data, hasError){ if (!hasError){ // No errors! Do your post and stuff // FYI, this will NOT set $_POST['ajax']... $.post(form.attr('action'), form.serialize(), function(res){ // Do stuff with your response data! if (res.result) console.log(res.data); }); } // Always return false so that Yii will never do a traditional form submit return false; }
You really don't need to do anything special on the controller side with the exception that if you know you are going to processing an AJAX request (ala
Yii::app()->request->isAjaxRequest
and no$_POST['ajax']
), you should be returning back a JSON object.For example
// Validate ok! Saving your data from form okay! // Send a response back! header('Content-type: application/json'); echo json_encode('result'=>true, 'data'=>$modelDataOrSomeJunkToGiveBackToBrowser); // Use CJSON::encode() instead of json_encode() if you are encoding a Yii model Yii::app()->end(); // Properly end the app
Edit: I should clarify, it is true that your actual Javascript function to submit the form won't create a
$_POST['ajax']
by default, but Yii doing the AJAX validation will (which already happened in the last AJAX request prior to calling your Javascript submit form function). So you can use the same logic in your controller for the AJAX validation as if you setCActiveForm.enableAjaxValidation
property totrue
.Not really work
'onkeypress'=>" if(event.keyCode == 13){ send(); } "
This part is trouble, imagine u have a richtext field...
Issue
var data=$("#person-form-edit_person-form").serialize();
How can pass the value to form id Dynamically using loop.
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.