Thursday, 25 November 2021

How to ensure that no data get lost while transferring them to and storing them on the server?

JavaScript:

const XHR = new XMLHttpRequest();

function sendData(data) {
  XHR.open('POST', 'savedata.php');
  XHR.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  XHR.send('data=' + JSON.stringify(data);
}

PHP:

if (isset($_POST['data'])) {
    if (file_exists('data.json')) {
        $file = file_get_contents('data.json');
        $accumulatedData = json_decode($file);
        $data = json_decode($_POST['data']);
        array_push($accumulatedData, $data);
        $encodedAccumulatedData = json_encode($accumulatedData);
        file_put_contents('data.json', $encodedAccumulatedData);
    }
}

If the intervals between the data transfers are very short, data get lost. How to prevent this?



from How to ensure that no data get lost while transferring them to and storing them on the server?

No comments:

Post a Comment