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?
– BrTkCa
When I try to show
xhr.responseText
on the console, comes out blank. When I check the type ofxhr.responseText
, is a string type.– Amanda Lima
responseText: "true". This is not a valid JSON. Doc: http://www.json.org/json-pt.html
– mau humor
How can I get the
xhr.response
then?– Amanda Lima
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.
– mau humor
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.
– mau humor
How’s the part you set the url? like this:
xhr.open("GET", "ajax.php", true);
? With true as the last parameter?– mau humor
@mauhumor better not suggest that she use a synchronous request...
– bfavaretto
na vdd, wanted to identify the problem, before proposing solution.
– mau humor
I managed to solve, I put the solution in a reply
– Amanda Lima