1

I am having a little bit of trouble with my django project. Let's say, for example, I have a view written up to pull data from the database and return an array of names for a phonebook. When I put the returned data (phonebook contacts array) into an alert, the names come up fine, ex: "Adam", "Brittany", etc. When I console.log the returned data, the item names also are returned ("Adam", "Brittany", etc.). Using javascript, I am trying to get the data to display inside of a td cell, just the individual item names, so that there is a div for Adam, a div for Brittany, etc. Unfortunately, instead of displaying the contact names, my code is displaying [Object object] multiple times. How do I get the contact name to take place of [Object object]? Why is [Object object] appearing instead? Thank you for any help you can provide.

My code is as follows:

/models.py:

class phonebook(models.Model):
    name = models.Charfield(max_length=200)
    phone_number = models.CharField(max_length=100)

/views.py:

def phonebook_home(request):
    global phonebook
    phonebook = phonebook.objects.order_by('name')

try:
    indexStart = int(request.GET.get('indexStart'))
    indexEnd = indexStart + 3
    next_three_contacts = phonebook.objects.order_by('name')[indexStart:indexEnd]

    serializer = contactSerializer()
    data = serializer.serialize(next_three_contacts)


    contact_count = phonebook.objects.count()
    moreAvailable = ''
    if indexEnd + 3 <= contact_count: 
        moreAvailable = 'more_than_two'
    elif indexEnd + 2 <= contact_count:
        moreAvailable = 'two_more'
    else:
        moreAvailable = 'no_more'
    return JsonResponse({'returned_contacts': data, 'moreAvailable': moreAvailable})
except:
    pass

/Serializers.py:

from django.core.serializers.python import Serializer 

class contactSerializer(Serializer):
    def end_object(self, obj):
        self._current['id'] = obj._get_pk_val()
        self.objects.append( self._current )

/main.js:

function generateCard(contactNameC, iconC) {
    var card = "<td class='tablecells'><a class='tabletext' href='#'><span class='fa "
            + iconC + " concepticons'></span><h2 class='header'>" + contactNameC
            + "</h2><p><span class='fa fa-chevron-circle-right'></span></p></a></td>";
    return card;
}


var indexLast = 9;
$(".showmorebutton").click(function() {
    var config = {
        type: 'GET',
        url: SUBMIT_URL,
        data: {
            indexStart: indexLast
        },
        dataType: 'json',
        success: function (data, textStatus_ignored, jqXHR_ignored)  {
            var moreAvailable = data.moreAvailable;
            var contacts = data.returned_contacts;
            var contactNameLoop = $.each(contacts, function(idx, obj) {
                    console.log(obj.name);
                    alert(obj.name)
                }); 

            if (moreAvailable === "more_than_two") {
                $("table").append("<tr></tr>");
                for (var i = 0; i < 3; i++) {
                var contactName = contactNameLoop[i]
                var icon = "fa facogs";
                $("table tr:last").append(generateCard(contactName, icon));
                }
            }
        }
    };
    $.ajax(config);
    indexLast += 3; 
});

edit:

I also made sure to import the proper modules/files into each python file.

3
  • Log all of obj to the console and see what the structure is. Commented Jan 6, 2015 at 15:06
  • @DanielRoseman When I do that it displays the next three contact names 3 times each. Ex: Joe Sarah John Joe Sarah John Joe Sarah John Commented Jan 6, 2015 at 15:10
  • Screenshot example: postimg.org/image/v6xlqtizh Commented Jan 6, 2015 at 15:14

1 Answer 1

2

Your iterations will never yield 1 name at a time since your $.each is iterating over all of the contacts.

You should move your generateCard function within your contacts iteration and use the obj variable instead of passing the entire array (passing the entire array will either output undefined or [object Object]) into your generateCard function.

$.each(contacts, function(idx, obj) {
    var icon = "fa facogs";
    $("table tr:last").append(generateCard(obj, icon));
});    

Complete but contrived example and assuming a probably faulty json structure.

var contacts = [
  {name: 'henrik'},
  {name: 'sanaz'},
  {name: 'esther'},
];

var generateCard = function (obj, icon) {
  return "<tr><td>"+obj.name+'</td></tr>';
};
$("table").append("<tr></tr>");
$.each(contacts, function(idx, obj) {
    var icon = "fa facogs";
    $("table tr:last").append(generateCard(obj, icon));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table></table>

Update:

Your problem lies in your generateCard function, change contactNameC to contactNameC.name.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi! I refactored the AJAX call code and fixed it so now it returns one item at a time. Instead of returning [Object object] 3 times, it now displays it once. I updated my main.js file as stated above in the question. Do you know why it is still happening even after passing one item at a time?
It all depends on how generateCard function looks like. It's most likely in there.
Hmm, okay. I added in my code for the generateCard function up top if you don't mind taking a look at it, I would really appreciate it.
Awesome! Thank you for your help! It all makes sense now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.