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