Menus

Tuesday, 6 December 2016

Getting value form a table using Ajax

Yii2 Ajax Operations

Value selected from a database table using ajax in yii2

Example explains to get amount of Rate and Ta from  staffdetails table with depend on staff  drop down list changed in staff log book view.




First create tow tables staffdetails and stafflogbook and do CRUD operations of these tables.

Table staffdetails
Fields
id
staff_name
.
.
rate
ta
.
.

Table stafflogbook
Fields
id
staffdetails_id
.
.
.
.

Open staff log book view and add to javascript change event of staff dropdown list controller.

<?php

$script = <<< JS
    $('#stafflogbook-staffdetails_id').change(function(){
      var id = $(this).val();
        $.get("index.php?r=master/staffdetails/get-rate-ta", {staff_id : id}, function(data) {
        
        var data = $.parseJSON(data);  
        
        $('#stafflogbook-rate').attr('value',data.rate);
        $('#stafflogbook-ta').attr('value',data.ta);
        
        });
   });        
JS;
$this->registerJs($script);

?>


* Get some value form staffdetails for write a function in StaffdetailsController

     public function actionGetRateTa($staff_id){
        //Find the staff_id from the Staffdetails table
        $rate = Staffdetails::findOne(['id'=>$staff_id]);
        echo json::encode($rate);      
    }


So json need to add json helper class

use yii\helpers\Json;



Video  - Getting value form a table using Ajax





Error in Javascript Function Call On Yii2 Dropdown Active Form


HOW to Use onChange on DropDownList

onchange function in dropDownList yii2


Use

$this->registerJs($script, \yii\web\View::POS_END);

The last part means - add this script straightforward at the end of page.


Code add in header area on view form

<?php

...

$script = <<< JS
    $('#students-course_applied').change(function(){
      var id = $(this).val();
       
       
        alert(id);
       
        test();
       
   });  
     
        function test()
        {
        alert("Test Function");
        }
JS;
$this->registerJs($script, \yii\web\View::POS_END);

?>



Yii dropdown call javascript function


<?= $form->field($model, 'admission_mode')->dropDownList(
                    ArrayHelper::map(Groupitems::find()->andwhere(['category'=>13])->orderBy('description')->all(),'slid','description'),
                    ['prompt'=>'Select One' , 'onchange'=>'test();']
                    )   ?>








Thank you for visiting


No comments:

Post a Comment