Reputation: 31
I have a JavaScript function which is called with a parameter when someone clicks a div. The JavaScript function makes a JSON string out of the parameter and then makes a XMLHttpRequest (AJAX) to the php file that takes this JSON string, finds the number within the JSON string and then stores the number in a text file on the server.
However when i run this on my server, no number is appended to the text file and nothing seems to happen. No error message is displayed. The "Thank You!" message does get displayed in the div, which means the readystate does become 4 and the status does become 200.
The html code that calls the JavaScript function with a parameter:
<li id="star1" onclick="saveRating(1)"><i class="fa fa-star" aria-hidden="true"></i></li>
The javaScript function that creates a JSON string and calls the php file:
function saveRating(num){
obj = { "score":num };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//a "Thank You!" message is displayed in the div
}
};
xmlhttp.open("GET", "php/storeRating.php?x=" + dbParam, true);
xmlhttp.send();
}
The PHP file that opens a text file, searches the JSON string for a number and appends the number to the text file:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false); //gets the param that was sent and stores it in $obj
//opens text file and sets to appending the file.
$myfile = fopen("ratingNumbers.txt", "a");
//goes through string and if it finds a number it adds it to the text file.
while(false !== ($char = fgetc($obj))){
if($char == 1){
fwrite($myfile, $char);
}if($char == 2){
fwrite($myfile, $char);
}if($char == 3){
fwrite($myfile, $char);
}if($char == 4){
fwrite($myfile, $char);
}if($char == 5){
fwrite($myfile, $char);
}
}
//closes the file
fclose($myfile);
?>
[edit] The text file and PHP file both have write permissions.
Upvotes: 2
Views: 62
Reputation: 79
I found 2 mistakes on your script.
Place the file handle in given line while(false !== ($char = fgetc($myfile))){
$myfile = fopen("ratingNumbers.txt", "a+"); // Open for reading and writing;
Upvotes: 1