I am currently working on implementing ajax with django. However, I am encountering an error in the response.
When I send a request to the views using ajax and create a model, I encounter issues during the process of creation. It seems like there may be a problem with the return from the views.
The error message I receive is:
fail 200
(index):150 parsererror
(index):151 SyntaxError: Unexpected token a in JSON at position 0
at parse (<anonymous>)
at Ut (jquery-3.3.1.min.js:2)
at k (jquery-3.3.1.min.js:2)
at XMLHttpRequest.<anonymous> (jquery-3.3.1.min.js:2)
The javascript code (using jquery) looks like this:
$('form').on('submit', function(e){
let $submit_input = $(this).find('input')
let $data = $(this).data('group')
console.log($data);
e.preventDefault();
$.ajax({
'url': "{% url 'groups:ajax_post_add' %}",
'type': 'POST',
'data': {
'group': $data,
csrfmiddlewaretoken: '{{ csrf_token }}',
},
'dataType': 'json',
beforeSend: function(xhr, settings) {
$submit_input.attr('disabled', true);
}
}).then((...args) => { // done
const [data, textStatus, jqXHR] = args;
console.log('done', jqXHR.status);
})
.catch((...args) => { // fail
const [jqXHR, textStatus, errorThrown] = args;
console.log('fail', jqXHR.status);
console.log(textStatus);
console.log(errorThrown);
})
});
The python code for the views function (GroupRequestAdd) is as follows:
#views
@require_http_methods(["POST"])
def GroupRequestAdd(request):
group_id = request.POST.get('group')
group_id = group.objects.get(id=group_id)
request_add = belong.objects.create(user=request.user,group=group_id)
return HttpResponse("ajax is done!")