I have made an ajax request and it successfully queries the database, returning the desired data. However, I am facing a challenge in displaying this data on my page once it is received.
$.ajax({
url: '<?php echo \Yii::$app->getUrlManager()->createUrl('cases/ajax') ?>',
type: 'POST',
data: { firstcategory: firstcategory },
success: function(data) {
for (var key in data) {
var value = data[key];
alert(value);
document.write(value);
}
}
});
Although I am trying to display the value, it appears as an array when returned.
Here is the response from the ajax request:
Array
(
[0] => app\models\Subcategory Object
(
[_attributes:yii\db\BaseActiveRecord:private] => Array
(
[subcategory_id] => 1
[name] => ADJUDICATION ON BEHALF OF OR AGAINST AN INSOLVENT PARTY
[parent_id] => 2
)
[_oldAttributes:yii\db\BaseActiveRecord:private] => Array
(
[subcategory_id] => 1
[name] => ADJUDICATION ON BEHALF OF OR AGAINST AN INSOLVENT PARTY
[parent_id] => 2
)
...
)
[1] => app\models\Subcategory Object
(
...
)
[2] => app\models\Subcategory Object
(
...
)
)
Now, my goal is to display the specific data section below:
[subcategory_id] => 1
[name] => ADJUDICATION ON BEHALF OF OR AGAINST AN INSOLVENT PARTY
[parent_id] => 2
How can I achieve this using javascript when I receive the data in the variable "data"?
Thank you for any assistance provided.
Edit:
This is how my controller is structured:
public function actionAjax() {
if(isset($_POST['firstcategory'])) {
$firstcategory = $_POST['firstcategory'];
$subcategory = Subcategory::find()->all();
} else {
$firstcategory = "Ajax failed";
}
print_r($subcategory);
exit;
return \yii\helpers\Json::encode($subcategory);
}
Second edit:
The json I receive looks like this:
[
{
"subcategory_id": "1",
"name": "ADJUDICATION ON BEHALF OF OR AGAINST AN INSOLVENT PARTY",
"parent_id": "2"
},
{
...
}
]
In my view, I am attempting to parse it but encountering difficulties:
success: function(data) {
obj = JSON.parse(data);
document.write(obj.subcategory_id);
}
Why isn't this working as expected?