Assigning an array of objects within an AJAX request

I have a MediaObject object that includes:

  • a Media object
  • an array
  • and a function called getMedia()

When attempting to create a Media object and push it into the array inside the getMedia function after making an AJAX call, I encountered issues referencing the array. How should I properly reference it?

I have tried using both MediaObject.arrayList.push(mediaItem) and this.arrayList.push(mediaItem), but neither of them worked.

    function  MediaObject(){

            function Media(){
              this.id = "";
            }

            this.arrayList = [];

            AmebaObject.prototype.getMedia = function(){
              $.ajax({
                        url: this.rooturl+ this.loginurl,
                        type: 'GET',
                        headers: myheaders,
                        dataType: 'xml',
                        success: function (xml) {    
                             this.xml = xml;
                            $(xml).find("media").each(function(){
                               var mediaItem = new Media();
                               mediaItem.id = $(this).find('id').text();
                               MediaObject.arrayList.push(mediaItem);
                            });

                        },
                        error: function (xhr, textStatus, errorThrown) {
                            console.log("Status code : " + xhr.status);
                            console.log("Error: " + errorThrown);
                        }
                    });
            }

}

Error: Uncaught TypeError: Cannot call method 'push' of undefined

Answer №1

In order for the arrayList to be integrated into the MediaObject function, use the following code:

MediaObject.arrayList = [];

If you intend to access arrayList as a part of a MediaObject instance, you must adjust your reference within the success function.

Answer №2

It appears that there may be a misunderstanding in the usage of your MediaObject. At first glance, it seems like a constructor, but the way you are accessing MediaObject.arrayList implies it is a static property, which can be confusing.

Following user1329482's advice, you could utilize arrayList statically, with the caveat that it should be defined outside of the constructor to avoid resetting it for each new instance.

If your intention is to use it as an instance property, utilizing this is the only viable option. To access this within a callback's scope, you either need to define a local variable (often named var that = this) and access it accordingly, or employ the bind() method on your callback.

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

Lacking the knowledge on establishing range for amCharts

I am currently utilizing the amcharts plugin to generate visually appealing charts. While browsing through its features, I came across a few interesting ways to add ranges. However, I noticed that the structure of the code for these charts is different fro ...

New feature in Safari extension: transferring window object from inject script to global page

Is it possible to transfer the window object from an injected script to a global.html page? I am attempting to pass the window object as part of an object to the global page. However, when I try to dispatch the message from the "load" listener function, i ...

Setting default values for Vue prop of type "Object"

When setting default values for objects or arrays in Vue components, it is recommended to use a factory function (source). For example: foobar: { type: Object, default() { return {} } } // OR foobar: { type: Object, default: () => ({}) ...

Utilize Google Drive and scripts to incorporate map images into a React application

I'm currently working on setting up an album feature on my react website for a friend, and I would like the images in the album to be linked to a Google Drive so that he can easily upload new images whenever he wants. After successfully inserting the ...

Displaying postcode on a category page: A step-by-step guide

I would like to showcase the user input code and present it on the web exactly as entered. <?php #code... ?> Any assistance is greatly appreciated. Please excuse my English. Thank you! ...

Check input validations in Vue.js when a field loses focus

So I've created a table with multiple tr elements generated using a v-for loop The code snippet looks like this: <tr v-for="(item, index) in documentItems" :key="item.id" class="border-b border-l border-r border-black text ...

Can object methods be called using inline event attributes in an HTML tag?

Exploring the depths of core JavaScript has been my latest obsession. It's fascinating how we can easily trigger functions within the global context using events like this. HTML <span class="name" onclick="clicked()">Name</span> JavaSc ...

Present Different Content for Visitors Using Ad-Blocking Software

I am currently working on a project that is supported by ads. These ads are subtle and relevant to the content, not obnoxious popups for questionable products. However, since the project relies on ad revenue, users with Ad Blockers unfortunately do not co ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Verification of Form Submission

Looking for some help with web design, specifically regarding cache issues. I have a website where form data is submitted from form.php to buy-form.php. I'm trying to set up a cache error in Google Chrome so that when buy-form.php is accessed directl ...

Displaying dates on the Amcharts category axis for instances with empty data

I am currently creating a fruit consumption chart for each day, and so far everything is working correctly in the provided example. var chart = AmCharts.makeChart("chartdiv", { "type": "serial", "hideCredits": true, "fixedColumnWidth": '10px& ...

Organizing an array based on designated keywords or strings

Currently, I am in the process of organizing my logframe and need to arrange my array as follows: Impact Outcomes Output Activities Here is the initial configuration of my array: { id: 15, parentId: 18, type: OUTPUT, sequence: 1 }, { id: 16, parentId: ...

Guide on incorporating mouse movement while the mouse button is held down in JavaScript

For my project, I want to activate the mouse move event only when the mouse button is held down. I specifically need the action "OK Moved" to be triggered only when both the mouse button is held down and there is mouse movement. This is the code that I h ...

Obtain the key's name from the select query

My task is to populate a select element from JSON data, but the challenge lies in the formatting of the JSON where the keys contain important information. I do not have control over how the data is structured. I am attempting to iterate through the JSON a ...

React: Trying to use the map function on an empty array will result in an error

I am currently facing an issue while trying to populate a shopping cart with items. Even though I have initialized the cart as an empty array, I keep encountering the following error: TypeError: cart.map is not a function ProductContext.js:34 addItemToCar ...

Reordering sections in a dynamic manner

I'm working on a single-page website with four sections arranged like this: <section id=“4”> <section id=“3”> <section id=“2”> <section id=“1”> Now, I want to change the order of these sections when scrolling ...

Are items placed into an array passed by reference or by value?

When working with custom Objects in an Angular context, I define two objects "a" and "b" using an interface. These are created as class attributes along with an empty array of these objects. public a: CustomObj; public b: CustomObj; public array: ...

Adjusting the size of a Vue component on the fly

I'm struggling to find a way to dynamically adjust the width of a component. The component I am working with is called 'vue-burger-menu' -> https://github.com/mbj36/vue-burger-menu. To set the width, you need to assign a number to the prop ...

Locate a jquery element that is within a parent element containing specific text

This is the format I currently have: <td width="270px"> <img class="bullet" border="0" valign="top" src="gray-bullet.gif"> this is the text </td> Can someone provide me with a query to specifically target the img element with the class ...

The ApexChart Candlestick remains static and does not refresh with every change in state

I am currently working on a Chart component that retrieves chart data from two different sources. The first source provides historic candlestick data every minute, while the second one offers real-time data of the current candlestick. Both these sources up ...