I have an AJAX poll based on this tutorial: http://www.w3schools.com/php/php_ajax_poll.asp
However, instead of writing the poll entries from the HTML radio button to an array in a text file (as outlined in the tutorial). I would like to write to a JSON file. At the moment the values from the radio button entry are sent to the JSON, but the file does not retain the value between browser refreshes. I think that this is probably an issue with my syntax or encoding - the server should have the correct permissions to write to the file. Any tips are greatly appreciated.
<?php $vote = $_REQUEST['vote'];
//get content of json
$filename = "poll.json";
$poll = file_get_contents($filename);
$json = json_decode($poll);
//put content in array
$array = explode("||", $content[0]);
$yes = $array[0];
$no = $array[1];
if ($vote == 0) {
$yes = $yes + 1;
}
if ($vote == 1) {
$no = $no + 1;
}
//insert votes to json file
$insertvote = $yes."||".$no;
$fp = fopen($filename,"w");
fputs($fp,$insertvote);
$poll = json_encode($json);
fclose($fp);?>
At the moment the result is either: {1||} or {||1} in the JSON file, I can't figure out how to save the values the way that they were saved to the .txt file version (as outlined here: http://www.w3schools.com/php/php_ajax_poll.asp)
Update
So based on the excellent advice I received I am much closer. I found that "w" was the correct option for the php as "a+" appended data in the JSON rather than updating the existing values.
I now have a JSON file which is updating the values that are added through the html radio buttons.
So the result looks like: [3,4] AKA 3 votes from option 1 and 4 votes for option 2