Welcome to the LimeSurvey Community Forum

Ask the community, share ideas, and connect with other LimeSurvey users!

Error "Unexpected end of JSON input" (export responses from API with JavaScript)

  • constable_morty
  • constable_morty's Avatar Topic Author
  • Offline
  • New Member
  • New Member
More
1 year 3 months ago - 1 year 3 months ago #239723 by constable_morty
I am trying to export the responses of a survey with the remote control API with JavaScript (I am a beginner). With the following code, I manage to get the session key, when I run it in Node.js (I get CORS errors when trying to run it in the browser).
(How do I format code properly? The <pre> tag doesn't work)

Code:
let sessionKey = "";
 
const paramsGetSessionKey = {
method: "get_session_key",
params: ["myUsername", "myPassword", "Authdb"],
id: 1,
};
 
const optionsGetSessionKey = {
method: "POST",
mode: "cors",
body: JSON.stringify(paramsGetSessionKey),
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
},
};
 
fetch(
"https://mydomain.com/index.php/admin/remotecontrol",
optionsGetSessionKey
)
.then((response) => response.json())
.then((response) => {
console.log(response);
sessionKey = response.result;
});

As expected, I get the result 
Code:
{ id: 1, result: 'asdf123456789', error: null }

However, when I try to use the newly obtained session key to export responses, I get an error message (see below). I tried the following code:
Code:
const paramsExportResponses = {
method: "export_responses",
params: {
sessionkey: sessionKey,
surveyid: 12345,
documenttype: "csv",
},
jsonrpc: "2.0",
id: 1,
};
const optionsExportResponses = {
method: "POST",
mode: "cors",
body: JSON.stringify(paramsExportResponses),
contentType: "application/json",
dataType: "json",
};
fetch(
"https://mitwirk-o-mat.de/formular/index.php/admin/remotecontrol",
optionsExportResponses
)
.then((response) => response.json())
.then((response) => {
console.log(response);
});

The error message is
Code:
SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>;)
.

Does anyone know what I am doing wrong? Help is highly appreciated, thank you very much!

 
Last edit: 1 year 3 months ago by constable_morty.

Please Log in to join the conversation.

  • constable_morty
  • constable_morty's Avatar Topic Author
  • Offline
  • New Member
  • New Member
More
1 year 3 months ago - 1 year 3 months ago #239729 by constable_morty
I made some progress and found out that the line
Code:
 .then((response) => response.json())
caused the error. Now I'm getting a response, but I don't really know what to do with it. It looks like:
(I changed most numbers and strings just to be secure)
Code:
Response {
  [Symbol(realm)]: null,
  [Symbol(state)]: {
    aborted: false,
    rangeRequested: false,
    timingAllowPassed: true,
    requestIncludesCredentials: true,
    type: 'default',
    status: 200,
    timingInfo: {
      startTime: 55.555555555, // changed by me
      redirectStartTime: 0,
      redirectEndTime: 0,
      postRedirectStartTime: 55.5555555, // changed by me
      finalServiceWorkerStartTime: 0,
      finalNetworkResponseStartTime: 0,
      finalNetworkRequestStartTime: 0,
      endTime: 0,
      encodedBodySize: 20,
      decodedBodySize: 0,
      finalConnectionTimingInfo: null
    },
    cacheState: '',
    statusText: 'OK',
    headersList: HeadersList {
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: null
    },
    urlList: [ [URL] ],
    body: { stream: undefined }
  },
  [Symbol(headers)]: HeadersList {
    [Symbol(headers map)]: Map(15) {
      'server' => 'nginx',
      'date' => 'Sat, 21 Jan 2023 09:13:00 GMT',
      'content-type' => 'text/html; charset=UTF-8',
      'transfer-encoding' => 'chunked',
      'connection' => 'keep-alive',
      'vary' => 'Accept-Encoding',
      'set-cookie' => 'XX-XXXXXXXXXXXXXXX=478rhfeuk898484uoedj8334; path=/; secure; HttpOnly', // changed by me
      'expires' => 'Thu, 19 Nov 1981 08:52:00 GMT',
      'cache-control' => 'no-store, no-cache, must-revalidate',
      'pragma' => 'no-cache',
      'access-control-allow-origin' => '*',
      'x-xss-protection' => '1; mode=block',
      'referrer-policy' => 'strict-origin-when-cross-origin',
      'strict-transport-security' => 'max-age=63072000; includeSubDomains; preload',
      'content-encoding' => 'gzip'
    },
    [Symbol(headers map sorted)]: null
  }
}
Does anyone know, what I can do with this response to get my responses?
Last edit: 1 year 3 months ago by constable_morty.

Please Log in to join the conversation.

  • constable_morty
  • constable_morty's Avatar Topic Author
  • Offline
  • New Member
  • New Member
More
1 year 3 months ago - 1 year 3 months ago #239765 by constable_morty
I asked ChatGPT for help and together we could solve it. The solution was to decode the response with atob(), see code below. In this example, I just print the results to the screen, which is probably not what you want, but you can of course change it.

Code:
const paramsGetSessionKey = {
    method: "get_session_key",
    params: ["MyUserName", "MyPassword", "Authdb"],
    id: 1,
};
const optionsGetSessionKey = {
    method: "POST",
    mode: "same-origin", // Change if you make a cross-domain API call
    body: JSON.stringify(paramsGetSessionKey),
    headers: {
        "Content-Type": "application/json",
    }
};
fetch("https://mydomain.com/index.php/admin/remotecontrol", optionsGetSessionKey).then((response) => response.json()).then((response) => {
    let sessionKey = response.result;
    console.log(sessionKey);
    const paramsExportResponses = {
        method: "export_responses",
        params: {
            sSessionKey: sessionKey,
            iSurveyID: 1234556,
            sDocumentType: "csv",
            sResponseType: "long",
        },
        jsonrpc: "2.0",
        id: 1,
    };
    const optionsExportResponses = {
        method: "POST",
        body: JSON.stringify(paramsExportResponses),
        dataType: "text", // Change to JSON if you want JSON instead of CSV
        contentType: "application/json",
        mode: "same-origin", // See above
        headers: {
            "Content-Type": "application/json",
        }
    };
    fetch("https://mydomain.com/formular/index.php/admin/remotecontrol", optionsExportResponses).then((response) => response.json()).then((response) => {
        const csvContent = atob(response.result);
        console.log(csvContent);
        const output = document.createElement("p");
        output.textContent = csvContent;
        document.body.appendChild(output);
    });
});
Last edit: 1 year 3 months ago by constable_morty.
The following user(s) said Thank You: DenisChenu

Please Log in to join the conversation.

Lime-years ahead

Online-surveys for every purse and purpose