user10898133
user10898133

Reputation:

Error: Uncaught SyntaxError: Unexpected end of JSON input

There is the following script.

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();
    }
}

It is intended for an ajax request to the server. In response, from the server I pass json with the data. Empty json may come.

I get the following error.

Uncaught SyntaxError: Unexpected end of JSON input

Swears at this line - if (JSON.parse (ajax.responseText) .result == 'error') {

Json examples that may come

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'})

log

enter image description here

Upvotes: 1

Views: 9834

Answers (2)

Adamu Dankore Muhammad
Adamu Dankore Muhammad

Reputation: 147

I changed

res.status(204).json({ user });

To

res.status(200).json({ user });

And it worked like a charm!

Upvotes: 0

dirkgroten
dirkgroten

Reputation: 20682

The problem is you’re triggering your function on every state change of your xhr request. But not every state change means that a completed response has been sent.

Here is the list of state changes. As you can see, only the DONE state is relevant for parsing the response.

So in the other states your function will try to parse an empty responseText. Also you might have already a responseText in an earlier stage.

If you read the instructions you’ll see that the recommended event to listen to is the load event.

Upvotes: 1

Related Questions