Nanor
Nanor

Reputation: 2550

Displaying results of a HttpResponse after AJAX request

I have a page that on initial load displays all freelancers from the database. I've got a function that creates a POST request, passing the data of three select elements to retrieve specific matches from the database.

$(document).ready(function() {
    $('select.university').change(function(){
        $.ajax({
                type: 'POST',
                url: '#',
                data: {
                university: $('select.university').val(),
                skill: $('select.skill').val(),
                city: $('select.city').val()
                },
                dataType: 'html'
         });
         return false;
    });
});

My views get the data and return them through a HttpResponse:

def browse_freelancers(request):
    if request.method == 'GET':
        ...
    else:
        skills = request.POST.getlist('skill')
        universities = request.POST.getlist('university')
        cities = request.POST.getlist('city')

        # fetch from database

        return HttpResponse({'freelancers': freelancers,
                         'skills': skills,
                         'universities': universities,
                         'cities': cities})

The specific fetch is definitely being executed as I can step through it in my debugger but nothing changes in my HTML. What am I missing?

Upvotes: 0

Views: 1967

Answers (3)

Javier Clavero
Javier Clavero

Reputation: 447

Another possible structure:

if request.is_ajax() and request.method == 'POST':

    # ...

    response = {'freelancers': freelancers,
                     'skills': skills,
                     'universities': universities,
                     'cities': cities}

    return JsonResponse(response)

else:
    # ...   

Upvotes: 0

JRodDynamite
JRodDynamite

Reputation: 12613

In your views,

from django.utils import simplejson

def browse_freelancers(request):
     ...
     data = simplejson.dumps({'freelancers': freelancers,
                     'skills': skills,
                     'universities': universities,
                     'cities': cities})
     return HttpResponse(data)

If you are using Django 1.7+, then you can use JsonResponse instead of HttpResponse.

from django.http import JsonResponse
return JsonResponse({'foo':'bar'})

You need to set a success function in your $.ajax().

$.ajax({
    type: 'POST',
    ...
    success: function(data) {
        alert(data);
    }
});

Upvotes: 3

Remi Smirra
Remi Smirra

Reputation: 2539

You need to set dataType to 'json' and then in your view:

return HttpResponse(content=json.dumps({'freelancers': freelancers,
                     'skills': skills,
                     'universities': universities,
                     'cities': cities}))

Upvotes: 0

Related Questions