Reputation: 101
I have 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'm a beginner in Django, please help me.
Upvotes: 9
Views: 43795
Reputation: 12728
Just do this...(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 {
...
}
}
});
Upvotes: 1
Reputation: 4320
how about create dict and parse to json:
name = request.POST.get('name')
dict = {'name':name}
return HttpResponse(json.dumps(dict), content_type='application/json')
Upvotes: 10
Reputation: 10454
You have a typo:
success: function(resp){
alert ("resp");
}
should be
success: function(resp){
alert (resp);
}
Also, regarding csrf, you must use the header like this:
$.ajax({
url: "some-url",
headers: {'X-CSRFToken': '{{ csrf_token }}'},
Upvotes: 2
Reputation: 1983
if nothing works, put "@csrf_exempt" before your function
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def lat_ajax(request):
"""
your code
"""
Upvotes: 0
Reputation: 43096
Put dataType: "json"
in the jquery call. The resp will be a javascript object.
$.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. The content_type must be application/json
. In this case, the locals trick is not recommended because it is possible that some local variables can not be serialized in json. This wil raise an exception. Please also note that is_ajax
is a function and must be called. In your case it will always be true. I would also test request.method
rather than 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 mentioned by Jurudocs, csrf_token can also be a cause I would ecommend to read : https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
Upvotes: 20
Reputation: 22808
$(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())
Upvotes: 0