Skip to content
Advertisement

Ajax “stack” variable into text file instead of posting it twice

So I am posting a variable to a .txt file the variable is 10 each time I post the variable the .txt simply keeps adding “10” instead of stacking it so on the first post it should be 10 and then on the second post it should be 20 and then on the 3rd it should be 30 how do I go about this? .txt file is blank here’s my code so far:

PHP:

<?php 
$Winner = $_POST['Winner'] ? $_POST['Winner'] : 'not set';
$file = fopen('file.txt','a+');
fwrite($file, $Winner.PHP_EOL);
fclose($file);
?>

Ajax:

$(document).on('click touchstart tap', '#submit', function() {

var Winner = 10;
 $.ajax({
    url:'rate.php',
    type:'post',
    data:{Winner:Winner},
    success:function(data){
       alert('Data Stored');
    } 
});
   
});

Advertisement

Answer

Read the file into a variable. Add the parameter to this, then write out the new value.

$score = intval(file_get_contents("file.txt"));
$score += intval($_POST['Winner']);
file_put_contents("file.txt", $score . PHP_EOL);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement