[Answered ]-Django ajax error

1👍

I think the problem is in return function. When you use an ajax you must not return it in render.

if request.is_ajax():
    return HttpResponse(datas, mimetype="application/javascript")
else:
    return render(request,'searchtrips.html',{'datas':datas})

1👍

The error means that your view is hanged or throwing exception.

First in you ajax, you should prevent it submit several times:

$("#routes").submit(function (e) {
    e.preventDefault();

    $.ajax({
        type: "POST",
        url: '/searchtrips/',
        datatype: 'html',
        data: {
            'city' : $('#city').val(),
            'location' : $('#location').val(),
            'duration' : $('#duration').val(),
            'csrfmiddlewaretoken': $('input[name=csrfmiddlewaretoken]').val()
        },                    
        success: function (resp) {
            console.log('Success');
            $('#routeTable').html(resp);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log('Error');
            console.log(jqXHR);
            console.log(textStatus);
            console.log(errorThrown);
        }
    });
});

Next in your view, you might want to catch exception if there is any:

def SearchTrips(request):
    city = request.POST['city'].replace(" ","%20")
    location = request.POST['location'].replace(" ","%20")
    duration = request.POST['duration']
    url = "http://blankket-mk8te7kbzv.elasticbeanstalk.com/getroutes?city=%s&location=%s&duration=%s" % (city, location, duration)

    try:
        resp = urllib2.urlopen(url)
    except:
        resp = None

    if resp:
        datas = json.load(resp)
    else:
        datas = None

    return render(request, 'searchtrips.html', {'datas': datas})

Also make sure that you read PEP 8 since your code styling and naming convention is quite bad.

Hope it helps.

0👍

Here is my new ajax.js code(just to close this thread and for anyones future reference)

$(function(){

    $('#searchtest').click(function() {

        $.ajax({
            type: "POST",
            url: "/searchtrips/",
            data: {
                'city' : $('#city').val(),
                'location' : $('#location').val(),
                'duration' : $('#duration').val(),
                'search_text' : $('#searchtest').val(),
                'csrfmiddlewaretoken' : $("input[name=csrfmiddlewaretoken]").val()
            },
            success: searchSuccess,
            dataType: 'html'
        });

    });

});

function searchSuccess(data, textStatus, jqXHR)
{
    $('#search-results').html(data);
}
👤Mayank

Leave a comment