show questions one at a time in quiz website in html - javascript

I have done a quiz website which shows a question and 4 options with radio button. the questions are fetched from database. but all questions are showing up all at a time. i want to show one question at a time when the user clicks the option. soon after he clicks the option the current question should fade and show the next question. i have tried many ways using javascript and all but nothing is working. can anyone help me. here is my html code
<div class="services">
<div class="container">
<?php $response=mysql_query("select * from questions");?>
<form method='post' id='quiz_form'>
<?php while($result=mysql_fetch_array($response)){ ?>
<div id="question_<?php echo $result['id'];?>" class='question'> <!--check the class for plurals if error occurs-->
<h2 id="question_<?php echo $result['id'];?>"><?php echo $result['id'].".".$result['question_name'];?></h2>
<div class='align'>
<input type="radio" value="1" id='radio1_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
<label id='ans1_<?php echo $result['id'];?>' for='1'><?php echo $result['answer1'];?></label>
<br/>
<input type="radio" value="2" id='radio2_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
<label id='ans2_<?php echo $result['id'];?>' for='1'><?php echo $result['answer2'];?></label>
<br/>
<input type="radio" value="3" id='radio3_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
<label id='ans3_<?php echo $result['id'];?>' for='1'><?php echo $result['answer3'];?></label>
<br/>
<input type="radio" value="4" id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
<label id='ans4_<?php echo $result['id'];?>' for='1'><?php echo $result['answer4'];?></label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $result['id'];?>' name='<?php echo $result['id'];?>'>
</div>
<br/>
<input type="button" id='next<?php echo $result['id'];?>' value='Next!' name='question' class='butt'/>
</div>
<?php }?>
</form>
</div>
</div>

that is because you're using select * from questions, this will fetch everything in the questions database, what you would be doing is requesting one question at a time select * from questions LIMIT 0, 1 // index_from, amount, And then next time increase your limit with one LIMIT 1, 1

A general and efficient approach to achieve this by loading the question in UI one at a time, when your desired event fired in UI.
Lets elaborate the strategy here
Step 1: there will be js function call to load the desired question.
the desired or existing question id will be argument to this js
function.
Step 2 the js function will have a ajax call to a php sript with the argument.
Step 3 backend php should return a json object array with desird question and option.
Step 4:js function should now arrange to print the return value accordingly

YOU CAN TRY THIS OUT:
php code can be:
$sql = "SELECT * FROM questions";
if ($result = $conn->query($sql)){
// output data of each row
while ($row = $result->fetch_assoc()) {?>
<div id="question_<?php echo $row['id'];?>" class='question'>
<h2><?php echo $row['id'];?></h2>
<input type="radio" class="quiz-radio" name="<?php echo $row['id'];?>" value="<?php echo $row['answer1'];?>"><?php echo $row['answer1'];?>
<input type="radio" class="quiz-radio" name="<?php echo $row['id'];?>" value="<?php echo $row['answer2'];?>"><?php echo $row['answer2'];?>
<input type="radio" class="quiz-radio" name="<?php echo $row['id'];?>" value="<?php echo $row['answer3'];?>"><?php echo $row['answer3'];?>
<input type="radio" class="quiz-radio" name="<?php echo $row['id'];?>" value="<?php echo $row['answer4'];?>"><?php echo $row['answer4'];?>
</div>
<?php }
} else {
echo "0 results";
}
js code :
jQuery(document).ready(function(){
jQuery('.question').hide();
jQuery('.question').first().show();
jQuery('.quiz-radio').change(function(){
console.log(jQuery(this).val());//display answer
var current=jQuery(this).closest('.question');
current.hide();
current.next().show();
});
});
NOTE: you need to call the js file in the .php or .phtml file.
I executed this code in my system , where all my questions and answers are in the database . i have stored them in a php variable.

Here I've made an example of how you can realize this solution. You will need 3 files.
1) Download jquery library and put it in site root folder, in this example I use jquery-3.3.1.min.js
2) Create file index.php with this content
<html>
<head>
<script src="jquery-3.3.1.min.js"></script>
</head>
<body>
<div class="services">
<div id="container"></div>
</div>
<script>
$(document).ready(function(){
$('body').on('click','#next', function(){
var curr_id = $(this).data('nextQuestion');
var answer1 = $('#radio1').is(':checked');
var answer2 = $('#radio2').is(':checked');
var answer3 = $('#radio3').is(':checked');
var answer4 = $('#radio4').is(':checked');
getQuestion(curr_id, answer1, answer2, answer3, answer4);
});
function getQuestion(curr_id, answer1=false, answer2=false, answer3=false, answer4=false){
$.post("ajax.php",
{
next_id: parseInt(curr_id)+1,
answer1: answer1,
answer2: answer2,
answer3: answer3,
answer4: answer4,
},
function(data, status){
$('#container').html(data);
});
}
getQuestion(-1);
});
</script>
</body>
</html>
2) Create ajax.php
<?php
$con=mysqli_connect("localhost","root","","quiz"); // change here to your data
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Check the number of all questions, if next_id is more than last question, back to first or whatever you want;
$response=mysqli_query($con,"select * from questions");
$number_of_all_questions = mysqli_num_rows($response);
if($number_of_all_questions <= $_POST['next_id']){
$_POST['next_id'] = 0;
}
// query next question
$response=mysqli_query($con,"select * from questions WHERE id =(select min(id) from questions where id > {$_POST['next_id']})");
?>
<?php while($result=mysqli_fetch_array($response,MYSQLI_ASSOC)){ ?>
<div id="question_<?= $result['id'] ?>" class='question'> <!--check the class for plurals if error occurs-->
<h2><?= $result['id'].".".$result['question_name'] ?></h2>
<div class='align'>
<input type="radio" value="1" id='radio1' name='1'>
<label id='ans1' for='1'><?= $result['answer1'] ?></label>
<br/>
<input type="radio" value="2" id='radio2' name='2'>
<label id='ans2' for='2'><?= $result['answer2'] ?></label>
<br/>
<input type="radio" value="3" id='radio3' name='3'>
<label id='ans3' for='3'><?= $result['answer3'] ?></label>
<br/>
<input type="radio" value="4" id='radio4' name='4'>
<label id='ans4' for='4'><?= $result['answer4'] ?></label>
</div>
<br/>
<input type="button" data-next-question="<?= $_POST['next_id'] ?>" id='next' value='Next!' name='question' class='butt'/>
</div>
<?php }?>
<?php mysqli_close($con); ?>

Related

How to sent id from one page to another when click on submit?

I have a database which consists of question_id, question, and options. Where I'll display the question and options. When the user clicked on submit I want to store the option they clicked and the question_id.
I am able to store the option they clicked but want to know how to store the question_id.
$user_email = $_SESSION['email'];
$query1="SELECT * FROM votes WHERE user_email='$user_email'";
$query2="SELECT * FROM poll_question WHERE status='1'";
$fetch2 = mysqli_query($con,$query2);
<html>
<head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="row">
<div class="col-md-6">
<?
while( $row2 = mysqli_fetch_array($fetch2))
{
?>
<form method="post" class="poll_form">
<h3><?echo $row2['question']?>?</h3>
<br />
<div class="radio">
<label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /><?echo $row2['option1']?></h4></label>
</div>
<div class="radio">
<label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /> <?echo $row2['option2']?></h4></label>
</div>
<br />
<?php
if( $count >0)
{ ?>
<button disabled="disabled" alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
<h>You selected : <? echo $row1['vote_option']; ?></h>
<br>
<p id="demo"></p>
<?php
}
else
{ ?>
<button alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
<?
}
?>
</form>
<? }
} ?>
<br />
</div>
</div>
<br />
<br />
<br />
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
$(".poll_form").submit(function(event){
event.preventDefault(); //prevents the form from submitting normally
var poll_option = '';
$('button.poll_option').each(function(){
if($(this).prop("checked"))
{
poll_option = $(this).val();
var option=poll_option;
}
var url = '<?php echo SITE_URL; ?>';
});
$.post("poll_vote.php",$('.poll_form').serialize(),
function(data)
{
if(data=="User Created Success"){
window.setTimeout(function () {
location.href ="<?php echo SITE_URL; ?>poll.php";
}, 100);
}
else{
$("#result").html(data);
}
}
);
//to reset form data
});
});
<? } ?>
</script>
</html>
Using th below function I am sending the poll_option to other where I kept the inset operation. Now I want to send the question_id also
Create a hidden input filed in your form
<input type="hidden" name="question_id" value="<?php echo $row2['question_id']; ?>">
Create a hidden input field in your form.
<input type="hidden" id="question_id" name="question_id" value="<?= $row2['question_id'] ?>">
PHP solution:
In this case your question_id will be included in the POST.
You can then access it by calling $_POST['question_id'].
Jquery solution:
In Jquery you can also access it by:
$("#question_id").val();

quiz next button not working when a json row is delete using php and jquery/javascript

i used the code below to create a quiz and it works well and nextbutton works perfect if the Que_id is for instance (1,2,3,4) but this will not work properlly (1,3,4) . as you can see, question id 2 has been deleted and this will result in many nextbutton instead of just normal One nextbutton.
But my problem is this, if i delete a row from the json file for example
"que_id":"1","que_desc":"The Best Coders Network","ans1":"Stackoverflow","ans2":"none","ans3":"none"}
or
{"que_id":"3","que_desc":"Stackoverflow was founded in what year","ans1":"2008","ans2":"none","ans3":"none"}
, the quiz will no longer be showing the quiz questions one by one via next button rather it will display all the nextbutton at once. If i then try to click any of the scattered next button, it will post the result.
on php end, It seems the quiz is submitted based on the que_id which is then passed to javascript incremented functions.
Can someone help me with this. I want the nextbutton to works perfect and display the quiz question one by one no matter which rows was deleted in json file.
below is the code
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset='utf-8'>
<script src="jquery.min.js"></script>
</head>
<body>
<?php
$data = '[{"que_id":"1","que_desc":"The Best Coders Network","ans1":"Stackoverflow","ans2":"none","ans3":"none"},
{"que_id":"2","que_desc":"Who Founded Stackoverflow","ans1":"Jeff Atwood and Joel Spolsky.","ans2":"none","ans3":"none"},
{"que_id":"3","que_desc":"Stackoverflow was founded in what year","ans1":"2008","ans2":"none","ans3":"none"},
{"que_id":"4","que_desc":"Stack Overflow is a privately held by a website","ans1":"Stack Exchange Network","ans2":"none","ans3":"none"}]';
$characters = json_decode($data);
//echo $characters->que_desc;
//echo print_r($characters);
//var_dump($characters);
?>
<form method='post' id='quiz_form'>
<?php
foreach ($characters as $value) {
$result['que_id']= $value->que_id ;
$result['que_desc']= $value->que_desc ;
$result['ans1']= $value->ans1 ;
$result['ans2']= $value->ans2 ;
$result['ans3']= $value->ans3 ;
?>
<div id="question_<?php echo $result['que_id'];?>" class='questions'>
<h2 id="question_<?php echo $result['que_id'];?>">
<?php echo $result['que_id'].".".$result['que_desc'];?>
</h2>
<div class='align'>
<label class="containerg">
<input type="radio" value="1" id='radio1_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans1_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans1'];?></label>
<span class="checkmark"></span>
</label>
<label class="containerg">
<input type="radio" value="2" id='radio2_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans2_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans2'];?></label>
<span class="checkmark"></span>
</label>
<label class="containerg">
<input type="radio" value="3" id='radio3_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans3_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans3'];?></label>
<span class="checkmark"></span>
</label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $result[' que_id '];?>' name='<?php echo $result[' que_id '];?>'>
</div>
<br/>
<input type="button" id='next<?php echo $result[' que_id '];?>' value='Next!' name='question' />
</div>
<?php }?>
</form>
<div id='result'>
Result will Appear Here test
<br/>
</div>
<script>
$(document).ready(function() {
var steps = $('form').find(".questions");
var count = steps.size();
steps.each(function(i) {
hider = i + 2;
if (i == 0) {
$("#question_" + hider).hide();
createNextButton(i);
} else if (count == i + 1) {
var step = i + 1;
$("#next" + step).on('click', function() {
submit();
});
} else {
$("#question_" + hider).hide();
createNextButton(i);
}
});
function submit() {
// post to ajax
$.ajax({
type: "POST",
url: "ajax.php",
data: $('form').serialize(),
success: function(msg) {
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#result').append(msg);
}
});
}
function createNextButton(i) {
var step = i + 1;
var step1 = i + 2;
$('#next' + step).on('click', function() {
$("#question_" + step).hide();
$("#question_" + step1).show();
});
}
});
</script>
</body>
</html>
The problem with your code the that you are creating element using the data with given id values and in your jQuery event bind logic you assume that these values are always in continuation.
If you remove any row from the data the continuation and the logc both will be broken.
You need to update your logic based on the class selector.
You can update your code logic like this.
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset='utf-8'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<?php
$data = '[{"que_id":"1","que_desc":"The Best Coders Network","ans1":"Stackoverflow","ans2":"none","ans3":"none"},
{"que_id":"2","que_desc":"Who Founded Stackoverflow","ans1":"Jeff Atwood and Joel Spolsky.","ans2":"none","ans3":"none"},
{"que_id":"3","que_desc":"Stackoverflow was founded in what year","ans1":"2008","ans2":"none","ans3":"none"},
{"que_id":"4","que_desc":"Stack Overflow is a privately held by a website","ans1":"Stack Exchange Network","ans2":"none","ans3":"none"}]';
$characters = json_decode($data);
//echo $characters->que_desc;
//echo print_r($characters);
//var_dump($characters);
?>
<form method='post' id='quiz_form'>
<?php
foreach ($characters as $value) {
$result['que_id']= $value->que_id ;
$result['que_desc']= $value->que_desc ;
$result['ans1']= $value->ans1 ;
$result['ans2']= $value->ans2 ;
$result['ans3']= $value->ans3 ;
?>
<div id="question_<?php echo $result['que_id'];?>" class='questions'>
<h2 id="question_<?php echo $result['que_id'];?>"><?php echo $result['que_id'].".".$result['que_desc'];?></h2>
<div class='align'>
<label class="containerg">
<input type="radio" value="1" id='radio1_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans1_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans1'];?></label>
<span class="checkmark"></span>
</label>
<label class="containerg">
<input type="radio" value="2" id='radio2_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans2_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans2'];?></label>
<span class="checkmark"></span>
</label>
<label class="containerg">
<input type="radio" value="3" id='radio3_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
<label id='ans3_<?php echo $result['que_id'];?>' for='1'><?php echo $result['ans3'];?></label>
<span class="checkmark"></span>
</label>
<input type="radio" checked='checked' value="5" style='display:none' id='radio4_<?php echo $result['que_id'];?>' name='<?php echo $result['que_id'];?>'>
</div>
<br/>
<input type="button" class="next" id='next<?php echo $result['que_id'];?>' value='Next!' name='question'/>
</div>
<?php }?>
</form>
<div id='result'>
Result will Appear Here test
<br/>
</div>
<script>
$(document).ready(function(){
var steps = $('form').find(".questions");
$(".questions").hide();
var count = steps.length;
steps.each(function(i){
if (i == 0) {
createNextButton(i);
$($(".questions").get(i)).show();
}
else if(count==i+1){
$($(".next").get(i)).off().on('click',function(){
submit();
});
}
else
{
createNextButton(i);
}
});
function submit(){
// post to ajax
$.ajax({
type: "POST",
url: "ajax.php",
data: $('form').serialize(),
success: function(msg) {
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#result').append(msg);
}
});
}
function createNextButton(i){
$($(".next").get(i)).on('click',function(){
$(".questions").hide();
$($(".questions").get(i+1)).show();
});
}
});
</script>
</body>
</html>

How to continue two type of loop at a time using Javascript and PHP

I need one help.i need to continue 2 types of loop at a time using Javascript and PHP.Let me to explain my code and scenario as well.
<script>
function addQuestionField(){
var get =$("#ques").val();
if(get==null || get==''){
alert('Please add no of questions');
}else{
var counter = 0;
if (counter > 0){
return;
}else{
counter++;
<?php
$status=array("status"=>'1');
$feeddata=$db->kf_answertype->find($ustatus);
?>
for(var i=1;i<get;i++){
$('#container').append(' <textarea class="form-control" name="questions'+ i +'" id="questions" placeholder="Questions" style="background:#FFFFFF;" rows="2"><?php if($_REQUEST['edit']) { echo $getcustomerobj->questions; } else { echo $_REQUEST['questions']; } ?></textarea>');
<?php
foreach($feeddata as $v){
?>
$('#subcontainer').append(' <input type="radio" name="answer_type0" id="answer_type0" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?>');
<?php
}
?>
}
}
}
}
</script>
Here i have one for loop but inside this one foreach loop is still there .By doing this in one iteration of for loop foreach loop continuing many times which i dont need.Here i need each time of for loop the foreach loop also iterate.suppose for 1st iteration of for loop the foreach loop also iterate once and so on.Please help me.
Use current and next functions to get consistent elements of an array. So, this fragment of your code
foreach($feeddata as $v){
?>
$('#subcontainer').append(' <input type="radio" name="answer_type0" id="answer_type0" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?>');
<?php
}
?>
should be changed to
$('#subcontainer').append(' <input type="radio" name="answer_type0" id="answer_type0" value="<?php echo current($feeddata)['_id']; ?>"> <?php echo current($feeddata)['answertype']; ?>');
<?php next($feeddata); ?>
or, if you use old version of php do it in such way:
<?php $v = current($feeddata); ?>
$('#subcontainer').append(' <input type="radio" name="answer_type0" id="answer_type0" value="<?php echo $v['_id']; ?>"> <?php echo $v['answertype']; ?>');
<?php next($feeddata); ?>

I am not able to get id through ajax from view to controller.but id is showing in alert box

This is view page code and I want to send id through this Ajax code but id is not posting in controller.I want to do question replacement one after another fetching from database.
$(document).ready(function()
{
$("#next").click(function()
{
var qid=$("#q").val();
alert(qid);
var d1=$("#r1").val();
var d2=$("#r2").val();
var d3=$("#r3").val();
var d4=$("#r4").val();
$.ajax({url:"<?php echo base_url().'index.php/ajax/question1';?>",data:{id:qid,a1:d1,a2:d2,a3:d3,a4:d4},success:function(data)
{
$("#dd").html(data);
}
});
});
});
HTML code:
<div id="dd">
<input type="text" name="ans" id="q" value="<?php echo $row->id?>">
Question:<label id="l1"><?php echo $row->q;?></label><br />
A:<input type="radio" id="r1" name="r" value="<?php echo $row->op1;?>"/><?php echo $row->op1;?><br />
B:<input type="radio" id="r2" name="r" value="<?php echo $row->op2;?> "/><?php echo $row->op2;?><br />
C:<input type="radio" id="r3" name="r" value="<?php echo $row->op3;?>" /><?php echo $row->op3;?><br />
D:<input type="radio" id="r4" name="r" value="<?php echo $row->op4;?>" /><?php echo $row->op4;?> <br />
</div>
<input type="button" id="next" value="Save and Next">
Here is Controller code
class ajax extends CI_Controller
{
public function question()
{
$this->load->model('model');
$r['row']=$this->model->qmodel();
if($r)
{
$this->load->view('q',$r);
}
}
public function question1()
{
$id=$this->input->post('id');
$a1=$this->input->post('a1');
$a2=$this->input->post('a2');
$a3=$this->input->post('a3');
$a4=$this->input->post('a4');
$ta=$this->input->post('ta');
$e=$id+1;echo $id;
echo $e;
}
}
As per docs if you don't specify request method default method of ajax is GET and in your controller your are accessing parameter using POST method
$.ajax({ type:'post' , url:'url '...

handling multiple buttons with same name and value in one form

I have multiple submit buttons on a site. They used to move elements up and down and I want to be them in one whole form in case of the user changes meanwhile some other values so everything is saved. The Problem now is I need the element ID of the button which was clicked.
So here is the code in the loop :
div class="form-order"><?php echo $elements[$z]['element_order']; ?> </div>
<input type="submit" name="edit_form_operation" value="▲" class="button-primary"
<?php if($elements[$z]['element_order'] == 1) echo 'disabled="disabled"'; ?> /><br />
<input type="submit" name="edit_form_operation" value="▼" class="button-primary"
<?php
$highest_element = $fdb->get_element_highest_order($form[$i]['form_id']);
if($elements[$z]['element_order'] == $highest_element) echo 'disabled="disabled"'; ?> />
And onclick of that specific button in the for loop he should write this code first so I know which element has to be moved
echo '<input type="hidden" name="change_element_id" value="'.$elements[$z]['element_id'].'" >';
I'm also open for another solution of this problem.
Ok I solved it like that now
Here you process the input:
// Select Operation
if(isset($_POST['edit_form_operation_up'])) {
echo "move up id ";
$operation = array_keys($_POST['edit_form_operation_up']);
echo $operation['0'];
}
else if(isset($_POST['edit_form_operation_down'])) {
echo "move down id ";
$operation = array_keys($_POST['edit_form_operation_down']);
echo $operation['0'];
}
And this is in the for loop for infinite Elements the input with same value and name.
<?php $elements = $fdb->get_elements($form[$i]['form_id']);
for($z = 0; $z < sizeof($elements); $z++) {
?>
<tr>
<td><div class="form-order"><?php echo $elements[$z]['element_order']; ?> </div>
<input type="submit" name="edit_form_operation_up[<?php echo $elements[$z]['element_id']; ?>]" value="▲" class="button-primary"
<?php if($elements[$z]['element_order'] == 1) echo 'disabled="disabled"'; ?> /><br />
<input type="submit" name="edit_form_operation_down[<?php echo $elements[$z]['element_id']; ?>]" value="▼" class="button-primary"
<?php
$highest_element = $fdb->get_element_highest_order($form[$i]['form_id']);
if($elements[$z]['element_order'] == $highest_element) echo 'disabled="disabled"'; ?> />
</td>
<td><?php echo $elements[$z]['element_id']; ?> </td>
<td></td>
<td></td>
</tr>
<?php } ?>
In case of somebody finds this topic and want to find a good solution.
Greetings

Categories