I have code like this:
$(document).ready(function(){
$(\'#error\').hide();
$(\'#submit\').click(function(){
var name = $(\"#name\").val();
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 {
...
}
}
});
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
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')
$(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())
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
"""
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 }}'},