JSON.parse error: Unexpected end of JSON input

Asked

Viewed 32,001 times

6

I’m trying to get the answer to an xhr request:

...
xhr.send(formData);
var resposta = JSON.parse(xhr.responseText);
console.log(resposta); 
...

Console shows this error:

Uncaught SyntaxError: Unexpected end of JSON input

But I can’t see where I’m wrong. When I try:

console.log(xhr);

The console returns all right.

XMLHttpRequest {onreadystatechange: null, 
readyState: 1, 
timeout: 0, 
withCredentials: false, 
upload: XMLHttpRequestUpload…}
onabort: null
onerror: null
onload: null
onloadend: null
onloadstart: null
onprogress: null
onreadystatechange: null
ontimeout: null
readyState: 4
response: "true"
responseText: "true"
responseType: ""
responseURL: "******"
responseXML: null
status: 200
statusText: "OK"
timeout: 0
upload: XMLHttpRequestUploadwithCredentials: false__proto__: XMLHttpRequest
  • This message means that the string has an incompatible format in the JSON conversion. It can show us the output @Amandalima?

  • When I try to show xhr.responseText on the console, comes out blank. When I check the type of xhr.responseText, is a string type.

  • responseText: "true". This is not a valid JSON. Doc: http://www.json.org/json-pt.html

  • How can I get the xhr.response then?

  • Your problem at first is not with Javascript. You will have to change on the server that provides this answer. If you do not have control of this server. You can change Javascript and not treat the response with JSON.

  • It would look like this: xhr.responseText. But this does not contain a valid JSON, according to the log you showed. Then the problem is explained.

  • How’s the part you set the url? like this: xhr.open("GET", "ajax.php", true); ? With true as the last parameter?

  • @mauhumor better not suggest that she use a synchronous request...

  • na vdd, wanted to identify the problem, before proposing solution.

  • I managed to solve, I put the solution in a reply

Show 5 more comments

5 answers

5

I managed to solve the problem!

I added this line before sending the request, stating that the response will be text type:

xhr.responseType="text";
xhr.send(formData);

Then I added the excerpt below to get the reply of the request when it is completed:

xhr.addEventListener('readystatechange', function() {
    console.log(xhr.responseText); 
});
  • Edit the question.

  • 3

    @mauhumor, should not edit with the solution, otherwise the answers below lose coherence, I think as Amanda did, did well

  • 1

    In fact, within this event you need to do two checks, as the other answer indicates.

  • that goes for wordpress? Because I have the same mistake...

2

Hello Amanda your responseText is not a valid JSON, since it contains only a string "true".

responseText: "true"

I don’t think in this case you need to parse. A valid JSON example (returned by the server) would be:

{"resultado": "true"}

Update

According to the comments below, it must be happening that you try to get the result before the request has returned. So I’m going to leave an example request here. https://stackoverflow.com/questions/8567114/how-to-make-an-ajax-call-without-jquery

    <script type="text/javascript">
function loadXMLDoc() {
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
           if (xmlhttp.status == 200) {
               document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
           }
           else if (xmlhttp.status == 400) {
              alert('There was an error 400');
           }
           else {
               alert('something else other than 200 was returned');
           }
        }
    };

    xmlhttp.open("GET", "ajax_info.txt", true);
    xmlhttp.send();
}
</script>
  • So how do I get the responseText?

  • In fact you are doing this in this line: var reply = JSON.parse(xhr.responseText); . You can post your back-end code so we can see how the request response is being made?

  • 1

    @Amanda var resposta = xhr.responseText

  • always returns a string.

  • @bfavaretto, so it doesn’t work, returns an empty string.

  • Can you show the complete request code? Because if you are doing it asynchronously. You won’t be able to pick up the content of the reply right after send.

  • The problem is not the format, JSON.parse("true"); it should not fail: https://jsfiddle.net/ncjbastb/

  • True, the problem is that the request is asynchronous

  • And you’re right @Renan, strings are valid JSON

  • Thank you, I will update my reply. I think the problem should be in fact the request is asynchronous.

  • 2

    Really, this was the problem! I managed to solve, I will post an answer with what I did

  • 1

    so ... you’re welcome :D

Show 7 more comments

0

searching for an answer about the same error, I found that the return string contained accented characters and after removing worked, so that’s when I changed the format when saving the file to utf-8 because it was in ANSI and solved the problem (for me).

0

Putz I did different and made the same mistake. What I did was an ajax call with Jquery this way:

$.ajax({
    url: "/post/updatetags",
    type: "POST",
    data: JSON.stringify(obj),
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log("resposta: " + data)
        console.log("as tags foram atualizadas com sucesso!!!");
    },
    error : function(jqXHR, textStatus, errorThrown) {
        console.log("jqXHR: " + jqXHR.status);
        console.log("textStatus: " + textStatus);
        console.log("errorThrown: " + errorThrown);
    }
});

He arrived at the controller, but always gave the problem. Removing the

dataType: "json"

solved the problem

-1

It is also worth checking if you are using the correct PUT POST GET as well as Pathvariable and Requestparam

Browser other questions tagged

You are not signed in. Login or sign up in order to post.