0

I want to use data that was fetched using an AjaxQuery, parse that data and send the user to another view to do other stuff. However, I'm getting a Error 200 and a snippet of my test view and I have no idea why! The main idea of what I want to do is get the user location using a js function, then I use an AjaxQuery to get the coordinates, use POST in a view whose function is to handle the data and then send the user to another view where I can use those coordiantes to do other stuff.

AjaxQuery

$(document).ready(function(sol) {
    $("#send-my-url-to-django-button").click(function(sol) {
        $.ajax({
            url: "/establishments/process_url_from_client/",
            type: "POST",
            dataType: "json",
            data: {
                lat: sol[0],
                lon: sol[1],
                csrfmiddlewaretoken: '{{ csrf_token }}'
                },
            success : function(json) {
                alert("Successfully sent the URL to Django");

            },
            error : function(xhr,errmsg,err) {
                alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText);
            }
        });
    });
});

View.py

def get_coordinates_view(request):
return render(request, 'base2.html')

def process_url_from_client(request):
res = request.POST.get('data')
return render(request, "results.html")

Urls.py

urlpatterns = [
path("", views.get_coordinates_view),
path("process_url_from_client/", views.process_url_from_client),]

The results.html for now is just an html with hello, the error I get with this is: Could not send URL to django. Error 200: hello!

Thank you so much!

Dingo
  • 93
  • 1
  • 9

1 Answers1

0

Your error message is misleading you. There's no error sending the request to Django. However, there is an error in understanding the response.

You've told jQuery to expect a JSON response, by specifying dataType: "json" in the $.ajax call. But your Django view is not returning JSON, it is (for some reason) rendering an HTML template. As this answer demonstrates, when jQuery cannot parse a response according to the dataType it fires the error handler

Either drop that dataType, or preferably actually return JSON:

return JsonResponse({'message': 'ok'})
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895