Experiencing issues with retrieving data from an array returned by Django Rest Framework using AJAX, as it is showing as 'undefined'

I am facing an issue while trying to retrieve data from an array returned by an AJAX GET Request to Django Rest Framework. Despite console logging the data and identifying my target using index numbers, I keep encountering the undefined error. Even attempting to use JSON.parse() resulted in an error.

To provide a visual representation, here is what is printed by the console.log: Link to Image

Below is the relevant Javascript code snippet:

document.querySelector('#userLists').addEventListener('click', function(event) {
    if (event.target.dataset.name) {
      var listname = event.target.dataset.name
      console.log(listname);
      getTableData()
    }
})

const getTableData = function(){
  $.ajax({
      type: 'GET',
      url: '/api/uservenue/',
      data: {},
      success: function (data) {
        data.forEach(item => { 
              console.log(item.venue)
          })
          fillTable(data)
        }
      });
};

function fillTable(data)
{
  console.log(data)
  const table = document.getElementById("dashboardTableBody");
    let row = table.insertRow();
    let name = row.insertCell(0);
    name.innerHTML = data[0][1]; 
}

Here are the serializers used in DRF:

class mapCafesSerializer(serializers.ModelSerializer):
    class Meta:
        model = mapCafes
        fields = ['id', 'cafe_name', 'cafe_address', 'description']


class UserVenueSerializer(serializers.ModelSerializer):
    venue = mapCafesSerializer()
    class Meta:
        model = UserVenue
        fields = ['id', 'list', 'venue']

Additionally, here are the key models involved:

class UserVenue(models.Model):
    venue = models.ForeignKey(mapCafes, on_delete=models.PROTECT)  
    list = models.ForeignKey(UserList, on_delete=models.PROTECT)

class mapCafes(models.Model): 
    id = models.BigAutoField(primary_key=True)
    cafe_name = models.CharField(max_length=200)
    cafe_address = models.CharField(max_length=200)
    cafe_long = models.FloatField()
    cafe_lat = models.FloatField()
    geolocation = models.PointField(geography=True, blank=True, null=True)
    venue_type = models.CharField(max_length=200)
    source = models.CharField(max_length=200)
    description = models.CharField(max_length=1000)

    class Meta:
        managed = False
        db_table = 'a_cafes'


    def __str__(self):
        return self.cafe_name

Answer №1

Consider trying this:

name.innerHTML = data[0].venue.cafe_name; 

This change will access the correct property within the data array, which is structured as a one-dimensional array with object entries like {id, list, venue}. Attempting to access property 1 of an object entry as if it were an array results in undefined.

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

The act of including a get parameter compels middleware to carry out its function

I am currently using a middleware that looks like this // route middleware to verify a token app.use(function(req, res, next) { console.log(req.baseUrl); // check header or url parameters or post parameters for token var token = req.body.token | ...

In the event of a CI failure, what potential challenges might Django face?

Overview The configuration file for github-actions is described below. name: Django CI on: push: branches: [ "master" ] pull_request: branches: [ "master" ] jobs: build: runs-on: ubuntu-latest strategy: m ...

Can a seamless CSS transition be achieved at 0 degrees using transform:rotate(Xdeg)?

I am working on a React application that includes an icon positioned on a Leaflet map. The icon has a value ranging from 0 to 359 to represent its current direction. My goal is to use transform: rotate(Xdeg) to rotate the icon and implement a smooth anima ...

Iterating through a nested array of objects to merge and accumulate values

Just started learning Javascript. I've been trying to wrap my head around it for hours, looking at examples, but still struggling. I'm working with an array of objects that have nested properties which I need to loop through and consolidate. ...

Using bootstrap can alter the positioning of elements that have margins relative to other elements

After exploring suggestions from my previous post on Stack Overflow, I have implemented a modified version to animate drag movements. While the HTML5 draggable attribute can achieve dragging, its limitations and side effects are something I aim to avoid. ...

Django has detected an integrity error: it violates the not-null constraint

Developing a social media platform where every action is tracked and stored, I encountered an issue specifically with the like button. Even though the code for the like functionality mirrors that of the dislike function, I keep facing an error: IntegrityEr ...

What is the best location to keep a collection of strings that I plan to use for a specific function (temporarily)?

In the grand scheme of things, I manage a rather large and intricate (Django) application with an array of database tables. Currently, I am in the process of constructing the landing page for a fresh feature that entails a segment highlighting 3 randomly ...

Experience the feeling of releasing momentum by click and dragging the scroll

One feature I am looking for is the ability to control the scroll speed when dragging, and have the scroll continue moving slightly after release instead of stopping instantly. CodePen: https://codepen.io/rKaiser/pen/qGomdR I can adjust the speed adequat ...

Is there a "for each" option available in the GAE template?

Having trouble with the use of for each in GAE's template, which utilizes Django's template language. {% for blog_info in blog_archive %} {{ blog_info.time|date:"M Y" }} {% endfor %} I am attempting to limit the loop ...

What steps are involved in creating a custom cursor for a website?

Is there a way to customize the CSS cursor? CSS cursor customization I'm looking for the code to change the cursor on my website, similar to what is shown in the link below. Check out the Demo Here If possible, could someone provide a brief cod ...

How can I use JQuery to enable or disable checkboxes upon loading?

I am looking to implement a feature where the checkboxes are enabled when the .group is checked and disabled when it is unchecked. Although I can toggle between them, I'm facing difficulty in disabling the unchecked checkbox using the .group. Upon lo ...

What is the reason behind encountering this error message upon executing manage.py validate?

When I run manage.py validate, why am I encountering this error message?: Traceback (most recent call last): File "manage.py", line 11, in <module> execute_manager(settings) File "C:\python26\lib\site-packages\django&bsol ...

"How to change the hover background of a select element in Chrome from its default setting to something else

https://i.sstatic.net/G2deM.png Is there a way to remove the background color on hover and replace it with a different color? .drp-policydetails { border: 1px solid #dddddd; background-color: #ffffff; } <div className="form-group"> <sele ...

Identifying Javascript-Set Cookies on the Client-Side: A Comprehensive Guide

Currently, I am using Python and Selenium for my project. I'm trying to determine if a specific cookie is set through JavaScript. Is there a method or approach that can help me accomplish this? ...

Guide on passing a shortened object to the view in Express.js

Hey there, I'm new to programming and currently working on setting up a basic blog using Express.js and Mongoose. In my code snippet below, I have successfully written a function that displays 6 articles from my database (each article has a simple Art ...

Next JS Dynamic Routing displays successful message on invalid routes

I have been using the App Router feature in Next JS along with Strapi as my CMS. When I make a query to the API endpoint in Postman, I receive the expected results. Requests for routes without corresponding slugs return a 404 error, while only routes with ...

Exploring Django Routing on Mac Operating System

After installing Django on my Mac, I tried specifying its path by adding it to .profile and verifying it with $PATH. However, when I attempted to import Django in Python's environment, it couldn't be found. Any suggestions on how to resolve this ...

Getting articles based on identification

I have received a JSON object from my WordPress site, here is what it looks like: { "ID": 4164, "title": "24-Hour Non-Stop with Marco Carola", "status": "publish", "type": "post", "author": { "ID": 11, ...

Nightmare JS randomly selecting and clicking on a link from a defined set

When coding with Nightmare JS, I am faced with a challenge. I want to click on a link using the method nightmare.click("#video-title"). However, this clicks the first element with that id. Upon running document.querySelectorAll('[id=video-title]' ...

Ways to retrieve the context of a function caller?

I'm exploring the concept of JavaScript scopes and am curious about a specific scenario: // B has access to 'context' var x = function (context) { y = function () { console.log(context); }; y(); }; x('cool'); ...