Home > Net >  Cant browse through Dictionary in Javascript
Cant browse through Dictionary in Javascript

Time:02-27

I am using Ajax to send data and as a success, it sends some data back.

            $.ajax({
                method: "POST",
                url: "{% url 'upload-prop-images' %}",
                processData: false,
                contentType: false,
                mimeType: "multipart/form-data",
                data: fileData,
                success: function (data) {

                    console.log(data);
                    console.log(data.newCard);
                    console.log(data.newCard.prop_name);

                    }
                }
            })

views.py :

def uploadPropImages(request):

    prop_obj = list(Property.objects.filter(user=request.user).values())
    new_card = {}
    for obj in prop_obj:
        if obj['prop_name'] == prop_name:
            new_card['prop_name'] = obj['prop_name']
            new_card['prop_address'] = obj['prop_address']
            new_card['prop_type'] = obj['prop_type']
            new_card['prop_images'] = '/media/'   obj['prop_images']

    return JsonResponse({'status': 'Done', 'newCard': new_card})

In the first code block where success: function(data) {}, console.log(data) prints the data I am sending, that is {'status': 'Done', 'newCard': new_card}, but when I print, console.log(data.status) or console.log(data.newCard), I get undefined value. I cant understand why it prints undefined because I used AJAX may times earlier and It seem to work. It is how we can browser through the value of a dictionary in JAVASCRIPT, which in PYTHON is print(data['status']). Is the error anything related to the keys defined inside the AJAX function: processData, mimeType, contentType?

CodePudding user response:

you need to call this

$.parseJSON();

Like this

               success: function (response) {
                var data= $.parseJSON(response);
                console.log(data);
                console.log(data.newCard);
                console.log(data.newCard.prop_name);

                }
  • Related