AJAX is not a new programming language, but a new way to use existing standards. AJAX is the art of exchanging data with a server, and updating parts of a web page – without reloading the whole page.
Scenarios:
- I have a database name city which contents the city name.
- I make a form to submit the city name and insert to database.
- This form is submitted when I hit enter or click submit button.
- After insert successful, it shows message “ Insert successful to database with ajax form submit method. ” without reloading the page.
- City.model
- AjaxForm.php
- AjaxSubmitController.php
DROP TABLE IF EXISTS `city`; CREATE TABLE `city` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `city` varchar(255) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
The exactly city.model after using gii tool will look like
<?php /** * This is the model class for table "city". * * The followings are the available columns in table 'city': * @property string $id * @property string $city * @property integer $country_id */ class City extends CActiveRecord { /** * @return string the associated database table name */ public function tableName() { return 'city'; } /** * @return array validation rules for model attributes. */ public function rules() { // NOTE: you should only define rules for those attributes that // will receive user inputs. return array( array('city', 'length', 'max'=>255), // The following rule is used by search(). // @todo Please remove those attributes that should not be searched. array('id, city, country_id', 'safe', 'on'=>'search'), ); } /** * @return array relational rules. */ public function relations() { // NOTE: you may need to adjust the relation name and the related // class name for the relations automatically generated below. return array( ); } /** * @return array customized attribute labels (name=>label) */ public function attributeLabels() { return array( 'id' => 'ID', 'city' => 'City', ); } /** * Retrieves a list of models based on the current search/filter conditions. * * Typical usecase: * - Initialize the model fields with values from filter form. * - Execute this method to get CActiveDataProvider instance which will filter * models according to data in model fields. * - Pass data provider to CGridView, CListView or any similar widget. * * @return CActiveDataProvider the data provider that can return the models * based on the search/filter conditions. */ public function search() { // @todo Please modify the following code to remove attributes that should not be searched. $criteria=new CDbCriteria; $criteria->compare('id',$this->id,true); $criteria->compare('city',$this->city,true); return new CActiveDataProvider($this, array( 'criteria'=>$criteria, )); } /** * Returns the static model of the specified AR class. * Please note that you should have this exact method in all your CActiveRecord descendants! * @param string $className active record class name. * @return City the static model class */ public static function model($className=__CLASS__) { return parent::model($className); } }
Secondly, the ajax_form.php file. This file contents the form which help us to do a submit by ajax jquery and display form.
<div class="form"> <?php $form=$this->beginWidget('CActiveForm', array( 'id'=>'ajax_form', 'enableAjaxValidation'=>false, 'htmlOptions'=>array( 'onsubmit'=>"return false;",/* Disable normal form submit */ 'onkeypress'=>" if(event.keyCode == 13){ sendSubmit(); } " /* Do ajax call when user presses enter key */ ), )); ?> <?php echo $form->errorSummary($model); ?> <div class="row"> <?php echo $form->labelEx($model,'city'); ?> <?php echo $form->textField($model,'city'); ?> <?php echo $form->error($model,'city'); ?> </div> <div class="row buttons"> <?php echo CHtml::Button('SUBMIT',array('onclick'=>'sendSubmit();')); ?> </div> <?php $this->endWidget(); ?> </div><!-- form --> <script src="http://code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript"> function sendSubmit() { var data=$("#ajax_form").serialize(); $.ajax({ type: 'POST', url: '<?php echo Yii::app()->createAbsoluteUrl("AjaxForm/ajax"); ?>', data:data, success:function(data){ alert(data); }, error: function(data) { // if error occured alert("Error occured.please try again"); }, }); } </script>
Line 6: I disable the default submit function of form. This default function will reload page when submit.
Line 7:
Call key press event. It means when we hit enter (key code is 13), it calls sendSubmit() javascript function.
In
sendSubmit()
function
function sendSumit() { var data=$("#ajax_form").serialize(); $.ajax({ type: 'POST', url: '<?php echo Yii::app()->createAbsoluteUrl("AjaxForm/ajax"); ?>', data:data, success:function(data){ alert(data); }, error: function(data) { // if error occured alert("Error occured.please try again"); }, }); }
Ajax jQuery will be called. It sends data which content form data above to AjaxForm controller and ajax action. It alerts return data
Controller file will be
<?php class AjaxFormController extends CController { public function actionAjax() { $model = new City(); if(isset($_POST['City'])) { $model->attributes=$_POST['City']; if($model->save()) { echo "Insert successful to database with ajax form submit method."; } } else { $this->render('AjaxForm',array('model'=>$model)); } } }
Line 6. Check if exists post method, it’ll do a save() and return successful message. If not, render and display the views page. (Line 15)
When it done, it looks like
Make a Ajax login form, go
.
Checking Ajax when login, go
.