Guide to displaying an array received from an Ajax Request in Yii2

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?

Answer №1

Modify this line

$subcategory = Subcategory::find()->all();

to

$subcategory = Subcategory::find()->asArray()->all();

this change will format the resultset into an array, allowing you to easily convert it to JSON.

Next, in your ajax success function, parse the JSON response.

var result = $.parseJSON(data);

for(var i=0; i<result.length; i++){
    alert(result[i].subcategory_id);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilize JQuery to implement fading effects for clicked elements in a webpage

I've been using a rollover JavaScript plugin to create smooth transitional effects when users hover over clickable page elements. Everything was going well until I decided to switch to making ajax calls instead of page loads for dynamic content. The p ...

Counting the distinct values in an array

I am working with an array named $countrySelected and I need to find the total unique count of countries in it. For example, if the array contains "Afghanistan," "Aland Islands," and "Afghanistan," the unique count would be 2. If you have any suggestions ...

Resolving CORS problem: Eliminating the 'Access-Control-Allow-Origin' Response Header in Angular

Recently, the backend API located at has been proxied by an F5 device which automatically includes the CORS header Access-Control-Allow-Origin: * in all responses. However, the GUI code seems to also be adding a CORS header with Access-Control-Allow-Origi ...

Updating an array of objects in React by setting a new value for a key

I am facing an issue with an array object called venue.products. It may or may not be pre-filled, depending on whether it has been saved previously. When the venue.products array is pre-filled, the code works fine and I can update it. However, if it is not ...

Is there a way to turn off _moz_resizing on my browser?

I am currently using the nicEdit editor and have successfully integrated my own custom image resizing script. However, I am facing an issue where the default _moz_resizing feature in Firefox is interfering with my custom script. My goal is to have specifi ...

Encountering difficulty retrieving a JSON array from a URL using Java

I am working with a servlet that emits a JSONArray, similar to a REST API. Despite following some guides and attempting to parse the URL, I'm struggling on how to actually do it. I've been successful in receiving the URL and printing it from my c ...

Discover the title of the selected checkbox

Looking for some help with a tricky problem I've encountered. I have created a script that identifies labels with a 'selected' class on their parent element, clones them, and appends them to an active list to create a 'Filtered Items&a ...

GraphQL Shield throws an 'Unauthorized' error for a permitted mutation

I've been working on setting up a GraphQL API with apollo-server-express, and I'm trying to handle permissions using graphql-shield middleware. However, I'm running into some issues when it comes to allowing mutations to be executed. My aim ...

Rely on the pre-installed package

Currently, I am creating a intelligent package that relies on 'showdown', a pre-installed Meteor package. How should I indicate this dependency? Even after adding packages: { 'showdown': {} } to smart.json, I encountered an error st ...

Applying CSS to select a different element style within a webpage

I was thinking about the possibility of linking one style to another using events like :focus or :hover in CSS alone, without the need for JavaScript. For instance, can the class "hitArea" change the background attribute of "changeArea" when it is in foc ...

Can the Twitter Bootstrap typeahead feature be used with an external data source?

Can the typeahead feature in version 2.0.3 of twitter-bootstrap work with a remote data source? You can check out the link for more information on the typeahead functionality: ...

Unusual behavior of leaflet maps in terms of size and tiling arrangements

Currently, I am in the process of integrating a leaflet map into my meteor-based website that utilizes blaze as its templating engine. I have encountered some peculiar issues regarding the map size and its behavior when dragging and zooming. The map init ...

How to Include Loading Animation in JQuery UI Ajax Tabs?

Is there a way to incorporate a loading graphic into the JQuery UI ajax tabs? I want it to pause for half a second, show the graphic, and then load the content. Below is the code snippet I currently have: <script type="text/javascript> $(function() ...

adding double quotes to each element of an array in PHP

My array is currently in the format shown below: $array = ["a, b, c, d"] However, I need to convert the array to the format shown below: $array = ["a","b","c","d"] I have searched on Google for a solution to this issue but have not found one that works ...

Tips for aligning an element vertically when it has a float using CSS or JavaScript

I am struggling with centering the image within the article list loop I created. The code snippet looks like this: <article class="article <?php if($i%2==0) { echo 'even'; } else { echo 'odd'; } ?>"> <section class ...

Display Image Based on Commencement Date and Conclusion Date

I am in need of some specific guidance as I have found myself overwhelmed and confused with my attempts so far. Hopefully, someone can provide the help I require. In my case, I have a collection of images each assigned certain start and end dates for disp ...

I am facing an issue with properly linking my jQuery

After searching through numerous posts on this website, I have yet to find a solution to my problem. My issue involves trying to implement a simple jQuery function that is not functioning as expected. It appears that the jQuery link may not be properly set ...

unable to retrieve the .id attribute from a resource

When attempting to access $scope.mySlot.id, it appears to be undefined. $scope.removeMe = function() { var shouldRemove = confirm('Are you sure you want to remove yourself from this field trip?'); ...

Transitioning to Meteor and React or Immigrating to Meteor

Are there any available resources specifically designed for Meteor that can assist with loading large assets (ranging from 20MB to 80MB) primarily for offline use? Currently, I am working on a project using Vanilla JS on the client side, but I am contempl ...

I am encountering a situation in which the controller file is returning empty data when logging the contents of req

User Model const mongoose = require("mongoose"); const userSchema = mongoose.Schema( { name: { type: String, required: true }, email: { type: String, unique: true, required: true }, password: { type: String, required: true }, pic: { ...