Undefined is getting displayed through jquery and json in yii2

Hi,

I am using Yii2 basic. I have a PHP function which takes 3 parameters GroupId, Year and Month and checks in the database whether there are records less than the selected year and month for groupId and which returns database records. In my case only one record is returned. I am using json_encode(). Data is correctly displayed in json format but undefined is returned when I call this method using $.post() as described below:

public function actionGroupsavinginfo($id,$year,$month)
{
$group = Yii::$app->db->createCommand('SELECT count(*)
FROM `groupsavingdetails`, groupdetails
where groupdetails.GroupId=groupsavingdetails.GroupId
and groupsavingdetails.Year<='.$year.'
and groupsavingdetails.Month<='.$month.'
and groupsavingdetails.GroupId='.$id
)
->queryScalar();


$groupsavingdetails = Yii::$app->db->createCommand('SELECT *
FROM `groupsavingdetails`
where
groupsavingdetails.Year<='.$year.'
and groupsavingdetails.Month<='.$month.'
and groupsavingdetails.GroupId='.$id
)
->queryAll();

if ($group == 0) {

echo $groupsavingdetails['OpeningBalance']=$groupsavingdetails['TotalValueofLoanGiven']=$groupsavingdetails['LoanRepaidUptilNow']=$groupsavingdetails['TotalValueOfLoanOutstanding']=0;
}
else {

$data = array();

foreach($groupsavingdetails as $groupsavingdetails1)
{

$data[] =$groupsavingdetails1;

}

return json_encode($data);

}
}

In the form I use jquery $.post() as follows

$.post("index.php?r=groupsavingdetails/groupsavinginfo&id='.'"+$("select#groupsavingdetails-groupid").val()+"&year='.'"+$("input#groupsavingdetails-year").val()+"&month='.'"+$("select#groupsavingdetails-month").val(),function(data) {
			console.log(data);

			  
				$("input#groupsavingdetails-openingbalance").val(""+data[0].ClosingBalance);


});

Here in console.log(data) data is displayed but data[0].ClosingBalance gives undefined.

What should I do?

I think you’re not setting the correct headers in your controller.

Instead of return json_encode($data); try this:

Yii::$app->response->format = Response::FORMAT_JSON;
return $data;

Please note that the function echo directly something also will affect the client side to identify the proper JSON object

Thanks it is working.

These lines of code are EXTREMLY DANGEROUS. Please protect your app against SQL INJECTION attack.

Take a look at this, PLEASE.
https://www.yiiframework.com/doc/guide/2.0/en/security-best-practices#avoiding-sql-injections

I generally return json data as

return $this->asJson($data);

Thanks. It’s correct, I had made changes by binding the values.

2 Likes