JSON.parse error: Unexpected end of JSON input

2

I'm trying to get the response from a xhr request:

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

Console displays this error:

Uncaught SyntaxError: Unexpected end of JSON input

But I can not 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
    
asked by anonymous 12.01.2017 / 17:44

3 answers

3

I was able to solve the problem!

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

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

Then I added the snippet below to get the request response when it is complete:

xhr.addEventListener('readystatechange', function() {
    console.log(xhr.responseText); 
});
    
12.01.2017 / 18:13
1

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

responseText: "true"

I think in this case you do not need to parse. A valid JSON sample (returned by the server) would be:

{"resultado": "true"}

Update

As the comments below, it must be happening that you try to get the result before the request has returned. So I'll leave here an example of a request. link

    <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>
    
12.01.2017 / 17:51
0

I'm trying this same problem. I read your answer but could not apply it to my code. Do you mind helping me?

This is the error that is appearing:

VM10097: 1 Uncaught SyntaxError: Unexpected end of JSON input     at JSON.parse ()     at XMLHttpRequest.

Here's my code:

 function montaAula(){


  let montarAula = {

    idUsuario: document.querySelector('#id').textContent,
    token: document.querySelector('#token').textContent,
    id: document.querySelector('#ultima-aula').textContent
  };

  var xhr = new XMLHttpRequest();
  var variavel = document.querySelector('#token-servico').innerHTML;

  xhr.open("POST", "http://54.233.209.248:8080/rest/courses/findById", true);
  xhr.setRequestHeader("Content-type", "application/json");
  xhr.setRequestHeader("Authorization", "Bearer " + variavel);
  xhr.addEventListener("load", function(){

    if(xhr.status == 200){

      console.log(xhr.responseText);

      let curso = xhr.responseText;
      curso = JSON.parse(curso);

      let video = '';
      video += curso.video;
      document.querySelector('#video').innerHTML = video;

      let descricao ='';
      descricao += curso.descricao;
      document.querySelector('#curso-descricao').innerHTML = descricao;

    }
  });
  xhr.send(JSON.stringify(montarAula));
}

setTimeout(montaAula, 1000);
    
10.05.2018 / 22:36