[Solved] Jquery - 500 (Internal Server Error)

Hi All,

I’m trying to populate the ‘id’ textField based on a data from ‘department_id’ and ‘facility_id’ dropDownList.

Using this form;




<?php

/* @var $this ScaffoldController */

/* @var $model Scaffold */

/* @var $form CActiveForm */

?>


<div class="form">


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'scaffold-form',

	'enableAjaxValidation'=>false,

        'htmlOptions' => array('enctype' => 'multipart/form-data')

     )); ?>


	<p class="note">Fields with <span class="required">*</span> are required.</p>


	<?php echo $form->errorSummary($model); ?>

        

	<div class="row">

		<?php echo $form->labelEx($model,'department_id'); ?>

		<?php echo $form->dropDownList($model,'department_id', Department::model()->getDepartmentOptions(), array('prompt'=>'Select Department')); ?>

		<?php echo $form->error($model,'department_id'); ?>

	</div>

        

        <div class="row">

		<?php echo $form->labelEx($model,'facility_id'); ?>

		<?php echo $form->dropDownList($model,'facility_id', Facility::model()->getFacilityOptions(), array('prompt'=>'Select Facility')); ?>

		<?php echo $form->error($model,'facility_id'); ?>

	</div>


	<div class="row">

		<?php echo $form->labelEx($model,'id'); ?>

		<?php echo $form->textField($model,'id',array('size'=>11,'maxlength'=>7)); ?>

		<?php echo $form->error($model,'id'); ?>

	</div>

...



(Code suggested by a friendly Yii Forum Member)

Controller;




public function actionNewReferenceId()

            {

                $departmentId=null;

                $facilityId=null;

                if(isset($_GET['departmentId']))

                    $departmentId = $_GET['departmentId'];

                if(isset($_GET['facilityId']))

                    $facilityId = $_GET['facilityId'];


                //generateRef is the function in $model that calculates the new reference based on the department and facility 

                $ref = Scaffold::generateRef($departmentId,$facilityId);


                if($ref>0)

                     echo CJSON::encode(

                        array(

                            'status'=>'success', 

                            'newReferenceID'=>$ref,

                    ));

                else

                     echo CJSON::encode(

                        array(

                            'status'=>'error',

                            'message'=>'Invalid reference generated', 

                            'newReferenceID'=>$ref,

                    ));

            }



Model;




/*

         * returns generated reference if reference generated successfully, if not it returns 0

         */

        public static function generateRef($department_id,$facility_id){

                $newReference = 0;

                if($department_id && $facility_id){

                        $deptExists=Department::model()->exists('id=:id',array(':id',$department_id));

                        $facExists =Facility::model()->exists('id=:id',array(':id',$facility_id));

                        if($deptExists && $facExists){

                                $sql='SELECT max(id) as lastRef from tbl_scaffold where department_id=:dept_id and facility_id=:fac_id'; 

                                $command=Yii::app()->db->command($sql);

                                $command->bindParam(':dept_id',$department_id,PDO::PARAM_INT);

                                $command->bindParam(':fac_id',$facility_id,PDO::PARAM_INT);

                                $result= $command->queryRow();


                                if($result)

                                        $newReference =$result['lastRef']+1;

                                else{

                                        switch($department_id){

                                                case 1: //Ops & Maint

                                                        if($facility_id==1) //CUQ

                                                                $newReference=10001;

                                                        else if($facility_id==2) //DPP

                                                                $newReference=30001;

                                                         break;

                                                case 2: //AIMS

                                                        if($facility_id==1)

                                                                $newReference=50001;

                                                        else if($facility_id==2)

                                                                $newReference=70001;

                                                        break;

                                                case 3: //Shutdown

                                                        if($facility_id==1)

                                                                $newReference=80001;

                                                        else if($facility_id==2)

                                                                $newReference=90001;

                                                        break;


                                        }

                                }

                        }

                }

                return $newReference;

        }



View;




<?php 

Yii::app()->clientScript->registerScript("newreference","

        $('#Scaffold_department_id, #Scaffold_facility_id').change(function(e){

        

                        var departmentId = $('#Scaffold_department_id').val();

                        var facilityId= $('#Scaffold_facility_id').val();

        

                        if(departmentId && facilityId){

                        var info = { departmentId:departmentId,

                        facilityId:facilityId

        };

        

                        $.ajax({

                        url: '" . Yii::app()->createUrl("/scaffold/newReferenceId") . "',

                        data: info,

                        type: 'GET',

                        dataType: 'json',                      

                        success:function(data){

                        if(data.status=='success')

                        $('#Scaffold_id').val(data.newReferenceID);

        },

        });

        

        }

        });

");

?>



The script is being attached and the error is on PHP but I don’t know how to fix it. Please HELP.

Did you check the server error logs? If this does not help comment out everything and then uncomment your code piece by piece until the error occurs.

Hi dito,

No error logs on apache (httpd.conf - ErrorLog "logs/error.log") and php (php.ini - error_log = php_errors.log).

Is that the only option? check every piece of code?

Hi dito,

After playing several days with Chrome Developer tools, I came across this CDbException from the 500 error;




CDbCommand failed to execute the SQL statement: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens. The SQL statement executed was: SELECT 1 FROM `tbl_department` `t` WHERE id=:id LIMIT 1



Stack Trace




#2	

–  C:\Program Files\Apache Software Foundation\Apache2.4\htdocs\scaffreg\protected\models\Scaffold.php(323): CActiveRecord->exists("id=:id", array(":id", "1"))

318          * returns generated reference if reference generated successfully, if not it returns 0

319          */

320         public static function generateRef($department_id,$facility_id){

321                 $newReference = 0;

322                 if($department_id && $facility_id){

323                         $deptExists=Department::model()->exists('id=:id',array(':id',$department_id));

324                         $facExists =Facility::model()->exists('id=:id',array(':id',$facility_id));

325                         if($deptExists && $facExists){

326                                 $sql='SELECT max(id) as lastRef from tbl_scaffold where department_id=:dept_id and facility_id=:fac_id'; 

327                                 $command=Yii::app()->db->command($sql);

328                                 $command->bindParam(':dept_id',$department_id,PDO::PARAM_INT);

#3	

–  C:\Program Files\Apache Software Foundation\Apache2.4\htdocs\scaffreg\protected\controllers\ScaffoldController.php(197): Scaffold::generateRef("1", "1")

192                     $departmentId = $_GET['departmentId'];

193                 if(isset($_GET['facilityId']))

194                     $facilityId = $_GET['facilityId'];

195 

196                 //generateRef is the function in $model that calculates the new reference based on the department and facility 

197                 $ref = Scaffold::generateRef($departmentId,$facilityId);

198 

199                 if($ref>0)

200                      echo CJSON::encode(

201                         array(

202                             'status'=>'success', 



this lines are highlighted;




$deptExists=Department::model()->exists('id=:id',array(':id',$department_id));


$ref = Scaffold::generateRef($departmentId,$facilityId);



There it is, change your params array to:




$deptExists=Department::model()->exists('id=:id',array(':id'=>$department_id));



Thanks dito,

Another error after the changes:




CDbConnection and its behaviors do not have a method or closure named "command".


C:\Frameworks\yii-1.1.14\framework\base\CComponent.php(266)


254     public function __call($name,$parameters)

255     {

256         if($this->_m!==null)

257         {

258             foreach($this->_m as $object)

259             {

260                 if($object->getEnabled() && method_exists($object,$name))

261                     return call_user_func_array(array($object,$name),$parameters);

262             }

263         }

264         if(class_exists('Closure', false) && $this->canGetProperty($name) && $this->$name instanceof Closure)

265             return call_user_func_array($this->$name, $parameters);

266         throw new CException(Yii::t('yii','{class} and its behaviors do not have a method or closure named "{name}".',

267             array('{class}'=>get_class($this), '{name}'=>$name)));

268     }

269 

270     /**

271      * Returns the named behavior object.

272      * The name 'asa' stands for 'as a'.

273      * @param string $behavior the behavior name

274      * @return IBehavior the behavior object, or null if the behavior does not exist

275      */

276     public function asa($behavior)

277     {

278         return isset($this->_m[$behavior]) ? $this->_m[$behavior] : null;


Stack Trace

#0	

–  C:\Program Files\Apache Software Foundation\Apache2.4\htdocs\scaffreg\protected\models\Scaffold.php(327): CComponent->__call("command", array("SELECT max(id) as lastRef from tbl_scaffold where department_id=..."))

322                 if($department_id && $facility_id){

323                         $deptExists = Department::model()->exists('id=:id',array(':id'=>$department_id));

324                         $facExists = Facility::model()->exists('id=:id',array(':id'=>$facility_id));

325                         if($deptExists && $facExists){

326                                 $sql='SELECT max(id) as lastRef from tbl_scaffold where department_id=:dept_id and facility_id=:fac_id'; 

327                                 $command=Yii::app()->db->command($sql);

328                                 $command->bindParam(':dept_id',$department_id,PDO::PARAM_INT);

329                                 $command->bindParam(':fac_id',$facility_id,PDO::PARAM_INT);

330                                 $result=$command->queryRow();

331 

332                                 if($result)


#1	

–  C:\Program Files\Apache Software Foundation\Apache2.4\htdocs\scaffreg\protected\models\Scaffold.php(327): CDbConnection->command("SELECT max(id) as lastRef from tbl_scaffold where department_id=...")

322                 if($department_id && $facility_id){

323                         $deptExists = Department::model()->exists('id=:id',array(':id'=>$department_id));

324                         $facExists = Facility::model()->exists('id=:id',array(':id'=>$facility_id));

325                         if($deptExists && $facExists){

326                                 $sql='SELECT max(id) as lastRef from tbl_scaffold where department_id=:dept_id and facility_id=:fac_id'; 

327                                 $command=Yii::app()->db->command($sql);

328                                 $command->bindParam(':dept_id',$department_id,PDO::PARAM_INT);

329                                 $command->bindParam(':fac_id',$facility_id,PDO::PARAM_INT);

330                                 $result=$command->queryRow();

331 

332                                 if($result)



highlighted line:




$command=Yii::app()->db->command($sql);



Use createCommand() instead. Also see CDbConnection.




$command=Yii::app()->db->createCommand($sql);



Thank You So Much dito, It Works!

However if there’s no entry on database it returns a value of ‘1’ instead of the hardcoded value.

I think the error is on this lines:




if($result)

 $newReference = $result['lastRef']+1;



The value ‘1’ comes from +1 after [‘lasRef’], I tried to change if($result) to if($result>0) but the result is still the same. Just to test, else codes is working by changing the lines to:




if(!$result) and if($result==0)



What am I missing?, please help.

After testing all the posible codes, it finally works this way:




if($result['lastRef']>0)

 $newReference = $result['lastRef']+1;