0

I have to say that I have little to no experience with php and jquery. I currently have made a website which has multiple pages and each page has a question with either answer a or b. I'm trying to achieve that when the user clicks either a or b it saves it to a .txt file on my server. I have tried it with various tutorials but didn't seem to get it to work unfortunately. I hope someone can help me with creating a script.

Thanks!

Quincy Norbert
  • 431
  • 1
  • 6
  • 18

1 Answers1

0

First of all that is what databases are for. but assuming that you still want to write to .txt file,you need to make an ajax request to server with the content and have php write to that text file for you. Below are some sample codes for the same

function post(ans) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
    }
  };
  xhttp.open("GET", "/result.php?answer="+ans, true);
  xhttp.send();
}

and the php script for that would be

<?php
    $fname = "answer.txt";
    $result = $_GET["answer"];
    file_put_contents($fname,$result);
?>

assuming that you over-write the file each time, or

<?php
    $fname = "answer.txt";
    $result = $_GET["answer"];
    $prev = file_get_contents($fname);
    $result = $result.",".$prev;
    file_put_contents($fname,$result);
?>

also you can go fancy and json encode the data, but the right way to go would be to create a database

georoot
  • 3,557
  • 1
  • 30
  • 59
  • Thanks for the quick reply, but how would this work when every question is on a different page, I don't want the answers to overwrite all previous answers. How would I type the html? Would it be handy to share my code for this matter? – Quincy Norbert Apr 18 '16 at 11:38
  • @QuincyNorbert PHP script remains at the same url. you will need to add javascript to all the pages. And if you don't want to overide the previous answers have a look at my second part of code, that ought to point you to right direction. That being said i would recommend you to go with database for storing the answers – georoot Apr 18 '16 at 11:53