Data saving exampleΒΆ
Code on the server (to receive the data). Save this as save_data.php
<?php
$json = file_get_contents('php://input');
$obj = json_decode($json, true);
$username = explode("/", dirname(__FILE__))[2];
$server_data = '/home/'.$username.'/server_data';
$path = $server_data."/".$obj["filename"];
if (substr(realpath(dirname($path)), 0, strlen($server_data))!=$server_data) {
error_log("attempt to write to bad path: ".$path);
} else {
file_put_contents($path, $obj["filedata"], FILE_APPEND);
}
?>
The experiment (which sends the data).
<html>
<head>
<title>datasaving</title>
<script src="https://unpkg.com/jspsych@8.0.2"></script>
<script src="https://unpkg.com/@jspsych/plugin-image-keyboard-response@2.0.0"></script>
<script src="experiment.js"></script>
<link href="https://unpkg.com/jspsych@8.0.2/css/jspsych.css" rel="stylesheet" type="text/css" />
</head>
<body></body>
</html>
var jsPsych = initJsPsych({
on_finish: function() {
var experiment_data = jsPsych.data.get();
return save_data("test.csv", experiment_data.csv());
}
});
var factors = {
image: ['Dog1.jpg', 'Dog2.jpg', 'Dog3.jpg'],
duration: [400, 800, 1200]
};
var factorial_values = jsPsych.randomization.factorial(factors);
var trial = {
type: jsPsychImageKeyboardResponse,
prompt: '<p>Press a key!</p>',
stimulus: jsPsych.timelineVariable('image'),
trial_duration: jsPsych.timelineVariable('duration')
};
var trials_with_variables = {
timeline: [trial],
timeline_variables: factorial_values
};
async function fetch_with_retry(...args) {
let count = 0;
while(count < 3) {
try {
let response = await fetch(...args);
if (response.status !== 200) {
throw new Error("Didn't get 200 Success");
}
return response;
} catch(error) {
console.log(error);
}
count++;
await new Promise(x => setTimeout(x, 250));
}
throw new Error("Too many retries");
}
async function save_data(name, data_in){
var url = 'save_data.php';
var data_to_send = {filename: name, filedata: data_in};
await fetch_with_retry(url, {
method: 'POST',
body: JSON.stringify(data_to_send),
headers: new Headers({
'Content-Type': 'application/json'
})
});
}
jsPsych.run([trials_with_variables]);