0

I'm making a game of ludo, but in order to move you need to answer question correctly.

I have this onclick function that moves pieces:

if(getQuestion()){
  greenPieces[i].moveSmart(diceResult);
}

Basicly, function moveSmart will move pieces based on dice roll, and getQuestion will print a question, and if the answer to that question is correct, return true, if answer is wrong it will return false.

$(document).on("submit","form#ajax-panel", function(event){
  event.preventDefault();
  var dataObj2={
    answer: $("#answer option:selected").val(),
    answerWriten: $("#answerWrite").val(),
    correctAnswer: $("#correctAnswer").val(),
    difficulty: $("#questionDifficulty").val(),
  }
  console.log(dataObj2);

  $.ajax({
    url: 'ajax/checkAnswer.php',
    type: 'POST',
    dataType: 'json',
    data: dataObj2,
  })
  .done(function(data2) {
    console.log("Checking step completed");
    if (data2.answer == data2.correct) {
      console.log("true");
      $('#ajax-panel').html("");
      $('#ajax-panel').append("<p>Točno!</p>"); 
      return true;
    } else {
      console.log("false");
      $('#ajax-panel').html(""); 
      $('#ajax-panel').append("<p>Netočno!</p>"); 
      return false;
    }
  })

Both functions work independently, but I don't know how to make first function wait for second one. Full code is here, in jscode.js, function getQuestion is on line 546, and I call it from lines 439, 469, 492, 531. I've been stuck on this issue for 3 days and I tried multiple things with callbacks and timeouts but nothing worked.

Matus Dubrava
  • 13,637
  • 2
  • 38
  • 54
  • [A `Promise` is an object representing the eventual completion or failure of an asynchronous operation.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) – deEr. May 19 '18 at 10:11
  • Your `.done` will be executed after your submit event has finished, so this wont work this way. – Ivar May 19 '18 at 10:13
  • Don't use `.done()`, always use `.then()` – Bergi May 19 '18 at 10:51

0 Answers0