yii_king
(Micho23)
October 8, 2012, 12:14am
1
I have created an AJAX POST request to my controller and am able to send back a hardcoded value which is printed out in the view file.
However, when I query the database and try to return a json_encoded object, it just returns empty properties. The PHP code to query the db should be correct as I am using the exact same query to load the page the first time.
$sql = "SELECT * FROM tbl_p";
$p = ForecastManager::model()->findAllBySql($sql);
if ($p!=null){
print_r(json_encode(array(‘p’=>$p)));
return;
}
else {
print_r(json_encode("null"));
return;
}
The javascript used to print out the returned data looks like this:
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("f/s"); ?>',
data:data,
success:function(data){
alert(data);
},
error: function(data) { // if error occured
alert("Error occured.please try again");
alert(data);
},
dataType:'html'
});
So the javascript alert is then printing out this:
{"p":[{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{},{}]}
Any ideas of why it’s printing out empty values? How can I access each value returned?
Try this
$forecasts = ForecastManager::model()->findAll();
$attributes = array();
foreach ($forecasts as $forecast)
{
$attributes[] = $forecast->getAttributes();
}
echo json_encode($attributes);
Matt
abennouna
(Abennouna)
October 8, 2012, 6:51am
3
In addition to Matt’s suggestion, you should use ‘json’ in the ‘dataType’ property of your Ajax call (instead of ‘html’)
yii_king
(Micho23)
October 8, 2012, 8:57am
4
Thank you waterloomatt and bennouna for your answers.
After adjusting the code as suggested by you, it now prints out this:
[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
I’m now trying to access the properties of each object, but not getting it working. I’ve tried with this for example:
Any ideas about this?
yii_king
(Micho23)
October 8, 2012, 9:09am
5
yii_king:
Thank you waterloomatt and bennouna for your answers.
After adjusting the code as suggested by you, it now prints out this:
I’m now trying to access the properties of each object, but not getting it working. I’ve tried with this for example:
Any ideas about this?
I’ve solved this now by using this in the view file:
// Note that id should equal the property that you want to access
$.each(data, function(i, val) {
alert(val.id);
});
Many thanks again for your help.