I am trying to get data of user actions. I have two different scripts. The task is slightly different at each one. However, the part where I'm asking for the user name (which I use as a variable for the .csv data's name) and the php code are exactly the same. Though they are the same, I can get data as a csv file from one script but not from the other. What might be the problem here?
JS code for getting the subjectID:
var subjectID = prompt('What is your IU user name? (You need to type in your username so we can grant you credits for your participation. Otherwise, we will not know who you are.)');
if (subjectID === '' || subjectID == null) {subjectID=Math.floor(Math.random()*10000).toString()};
jsPsych.data.addProperties({subject_id: subjectID});
Function for saving the data:
function saveData(name, data){
var xhr = new XMLHttpRequest();
xhr.open('POST', 'write_data2.php'); // 'write_data.php' is the path to the php file described above.
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({filename: name, filedata: data}));
}
jsPsych.init({
timeline: timeline,
display_element: 'jspsych-target',
on_finish: function(){ saveData("IL" + subjectID + "_data", jsPsych.data.get().csv()); }
})
}
the content of write_data2.php file:
<?php
$post_data = json_decode(file_get_contents('php://input'), true);
// the directory "data" must be writable by the server
$name = "data/".$post_data['filename'].".csv";
$data = $post_data['filedata'];
// write the file to disk
file_put_contents($name, $data);
?>
finally, I have a folder called "data" at the same directory those scripts are in.