How to answer ajax request in Django

I have a code like this:

$(document).ready(function(){ $('#error').hide(); $('#submit').click(function(){ var name = $("#name").val(); if (name == "") { $("#error").show("slow"); return false; } var pass = $("#password").val(); if (pass == "") { $("#error").show("slow"); return false; } $.ajax({ url: "/ajax/", type: "POST", data: name, cache:false, success: function(resp){ alert ("resp"); } }); }); }); 

and view in Django:

 def lat_ajax(request): if request.POST and request.is_ajax: name = request.POST.get('name') return HttpResponse(name) else : return render_to_response('ajax_test.html',locals()) 

Where is my mistake? I am new to Django, please help me.

+4
source share
6 answers

Put dataType: "json" in the jquery call. A javascript object would be appropriate.

 $.ajax({ url: "/ajax/", type: "POST", data: name, cache:false, dataType: "json", success: function(resp){ alert ("resp: "+resp.name); } }); 

In Django, you must return a json-serialized dictionnary containing the data. Content_type must be application/json . In this case, the local residents trick is not recommended, as it is possible that some local variables cannot be serialized in json. This caused an exception. Also note that is_ajax is a function and should be called. In your case, this will always be true. I would also check request.method , not request.POST

 import json def lat_ajax(request): if request.method == 'POST' and request.is_ajax(): name = request.POST.get('name') return HttpResponse(json.dumps({'name': name}), content_type="application/json") else : return render_to_response('ajax_test.html', locals()) 

UPDATE: As Jurudocs mentioned, csrf_token could also be a reason I would recommend reading: https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax

+8
source

how about creating dict and parse for json:

 name = request.POST.get('name') dict = {'name':name} return HttpResponse(json.dumps(dict), content_type='application/json') 
+5
source

You have a typo:

  success: function(resp){ alert ("resp"); } 

it should be

  success: function(resp){ alert (resp); } 

In addition, with respect to csrf, you should use the header as follows:

  $.ajax({ url: "some-url", headers: {'X-CSRFToken': '{{ csrf_token }}'}, 
+1
source
 $(document).ready(function(){ $('#error').hide(); $('#submit').click(function(){ var name = $("#name").val(); if (name == "") { $("#error").show("slow"); return false; } var pass = $("#password").val(); if (pass == "") { $("#error").show("slow"); return false; } $.ajax({ url: "/ajax/", type: "POST", data: { 'name': name, 'csrfmiddlewaretoken': '{{csrf_token}}' }, contentType: "application/json;charset=utf-8", dataType: "json", success: function(data) { alert(data); }, error: function(ts) { alert(ts); } }); }); }); def lat_ajax(request): if request.POST: name = request.POST['name'] return HttpResponse(name) else : return render_to_response('ajax_test.html',locals()) 
0
source

If nothing works, put "@csrf_exempt" in front of your function

 from django.views.decorators.csrf import csrf_exempt @csrf_exempt def lat_ajax(request): """ your code """ 
0
source

Just do it ... (Django 1.11)

 from django.http.response import JsonResponse return JsonResponse({'success':False, 'errorMsg':errorMsg}) 

When you process the json part in jQuery, do:

 $.ajax({ ... dataType: 'json', success: function(returned, status, xhr) { var result = returned['success']; // this will be translated into 'true' in JS, not 'True' as string if (result) { ... else { ... } } }); 
0
source

All Articles