Chams Agouni
Chams Agouni

Reputation: 374

Access ajax elements with django

i am using ajax to fetch django model and get results

views.py

def browse_jobs(request):
    keyword = request.GET.get('keyword', None)
    company = Company.objects.filter(title__icontains=keyword)
    data = serializers.serialize("json", company, fields=('title'))
    return JsonResponse({'data':data,})

ajax request

$.ajax({
    url: '/browse_jobs',
    data: {
      'keyword': keyword,
    },
    dataType: 'json',
    success: function (data) {
      if (data) {
        console.log(data.title);
      }
    }
});

and i am getting this response from django

{"data": "[{\"model\": \"app.company\", \"pk\": 1, \"fields\": {\"title\": \"Facebook\"}}, {\"model\": \"app.company\", \"pk\": 2, \"fields\": {\"title\": \"Fabook\"}}]"}

my question is how i can access the title.

Upvotes: 1

Views: 30

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476594

You here double serialized the value for the "data" key: first by the serializers.serialize(..) that constructed a string, and the you again serialize it (constructing an string literal), making it harder to obtain the elements.

We can prevent this, for examply by turning the JSON blob back into a vanilla Python object first:

from json import loads as json_loads

def browse_jobs(request):
    keyword = request.GET.get('keyword', None)
    company = Company.objects.filter(title__icontains=keyword)
    data = serializers.serialize("json", company, fields=('title'))
    return JsonResponse({'data': json_loads(data), })

Then the AJAX call will receive a JSON blob where "data" does not map to a string, but a list of subdictionaries, making it easier accessible.

Here there are two results for your query, you can print the first title with:

$.ajax({
    url: '/browse_jobs',
    data: {
      'keyword': keyword,
    },
    dataType: 'json',
    success: function (data) {
        console.log(data.data[0].fields.title);
    }
});

Upvotes: 1

Related Questions