Jquery cannot trigger ajax call when end of quiz

Viewed 50

I have a simple quiz script, each question is display one after another when the answer is clicked, I want it when in the end of the quiz will send an ajax request to php for result processing and return as json, but it can't trigger any event after the last question, I've try alert() something by end of the question but nothing is happen with just blank page, I've check the console has nothing error too, please help to inspect what's goes wrong below:

var answers = [];

function nextQuestion() {
  var cq = $('.current.question');
  cq.removeClass('current');
  var hasNext = cq.next().length > 0;
  if (hasNext) {
    cq.next().addClass('current');
  } else {
    alert('you\'ve done!');
    $('body').append('<h2>Quiz completed</h2>');
  }
  return hasNext;
}

$('.question a').on('click', function(e) {
  e.preventDefault();
  var self = $(this);
  var ans = self.parent().index() + 1;
  answers.push(ans);
  var hasNext = nextQuestion();
  if (!hasNext) {
    alert('ajax send data to php');
    //will do ajax call here
  }
});
.question {
  display: none;
}

.question.current {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="question current">First question ?
  <ul>
    <li><a href="#">Answer A</a></li>
    <li><a href="#">Answer B</a></li>
    <li><a href="#">Answer C</a></li>
    <li><a href="#">Answer D</a></li>
  </ul>
</div>
<div class="question">Second Question ?
  <ul>
    <li><a href="#">Answer A</a></li>
    <li><a href="#">Answer B</a></li>
    <li><a href="#">Answer C</a></li>
    <li><a href="#">Answer D</a></li>
  </ul>
</div>
<div class="question">Third question ?
  <ul>
    <li><a href="#">Answer A</a></li>
    <li><a href="#">Answer B</a></li>
    <li><a href="#">Answer C</a></li>
    <li><a href="#">Answer D</a></li>
  </ul>
</div>
<div class="question">Last question ?
  <ul>
    <li><a href="#">Answer A</a></li>
    <li><a href="#">Answer B</a></li>
    <li><a href="#">Answer C</a></li>
    <li><a href="#">Answer D</a></li>
  </ul>
</div>

<!-- <script>/* here is where the script tag would be */</script> -->

I wish when the last question is click, some append message will show and trigger the ajax call as well.

Thanks!

2 Answers

You are only checking if there are any elements after the last question. Instead you need to check if their are any following .question elements.

e.g.

var hasNext = cq.next(".question").length > 0;

I've put your code in one file and it worked. wrapped your script in $(document).ready and put after jquery link. got the "ajax send data to php" alert also.

Related