Below is a script that handles AJAX requests:
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (JSON.parse(ajax.responseText).result == 'error') {
console.log('error')
$.each(JSON.parse(ajax.responseText).response, function(key, value) {
console.log(key)
$('.contact_form_' + key).css('display', 'block')
$('.contact_form_' + key).prev().css("border", '1px solid #FD7900')
$('.contact_form_' + key).text(value)
})
} else {
location.reload();
}
}
This script is designed for handling an AJAX request to the server. The expected response from the server is JSON data, which can sometimes be empty.
An error message may occur:
Uncaught SyntaxError: Unexpected end of JSON input
The error is usually associated with this line of code -
if (JSON.parse (ajax.responseText) .result == 'error') {
Here are some examples of the JSON responses that could be received:
if contact_form.is_valid():
contact_form = contact_form.save()
return JsonResponse({})
else:
response = {}
for k in contact_form.errors:
response[k] = contact_form.errors[k][0]
return JsonResponse({"response": response, 'result': 'error'})
Here is a log screenshot for reference: