Skip to content
Advertisement

Submit and POST “True” or “False” to a series of text questions presented one by one taken from a php array

new to forum, AJAX and JQuery. A little experience of PHP and JS.

I’m trying to present a long series of questions (400+) one by one in an input text field on a form with 2 submit buttons labelled “True” and “False”. I need one question to be presented at a time, then record the True or False result as (1 or -1) sequentially into another text file. I cannot refresh the input field with the next question after ‘Submit’. I believe that AJAX would be the answer. This code is the first effort: (any later efforts are more complicated, but don’t work any better) it opens the questions file (CPXQ.dat) into an indexed array, then places the first question into the input text field. When either of the submit buttons are pressed, the result is POSTed to data.cpx, and the next question appears, but it won’t continue thereafter. I have tried various PHP loops and some javascript, but these don’t work, either looping through immediately to the last question, or getting stuck in the loop. (The php includes just contain CSS and JQuery source.) I’d also like to prevent the user from being able to go back over any of the questions, but that may be a query for another day!

Any advice much appreciated, and apologies if not clear. Happy to provide any further info.

JavaScript

Here’s the code for the preliminary page collecting user details:

JavaScript

Advertisement

Answer

Using AJAX (fetch) is ideally suited to this type of problem where you do not wish to refresh the screen and want to present new data after submitting a http request. The following single page application shows how you might accomplish your stated goal but it does not take into account a couple of possible issues which are:

JavaScript

The issues mentioned could be negated by using a database to store answers and assigning the users unique identifiers (ie: user id, username) which is used when sending the ajax request.

The demo that follows will write, to the answerfile, either 1 or 0 ( which is more common than -1 for false ) alongside the question line number ( which is sort of the ID )

JavaScript

A sample of the answerfile:

JavaScript

I hope it helps you arrive at a solution but as mentioned it would be more robust / reliable with a database rather than simple text file.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement