I'm writing a quiz that sends an answer to the database via an asynchronous AJAX/JSON post. The database returns an indicator to tell if the answer was correct.
A colleague recommended using $.Deferred, since there is no way of telling how long it may take for the database call to return. I've been unable to find a clear example of doing this with an AJAX post. And I figured one of the StackOverflow experts could provide guidance on this.
This code is in the calling function which gets executed when a "Submit Answer" button is clicked.
var answerResult = recordAnswer(answer);
if (answerResult.IsAnswerCorrect) {
// Show student if her quiz answer was correct.
}
Here is the recordAnswer function. This needs to return a couple of values in an object (IsAnswerCorrect and IsQuizCompleted). My form is successfully making the AJAX call, and values are being returned to the 'result'. But sometimes the 'answerResult' value that gets returned comes back as 'undefined' in the calling code above, and consequently breaks. I believe changing this to a deferred call will avoid that problem.
var recordAnswer = function (answer) {
var quizSessionQuestionId = $('#hidden_quizSessionQuestionId').val();
var numberOfHintsUsed = 0;
var answerResult;
$.ajax({
url: QuizConfig.RecordAnswerDataAction, // Tied to RecordAnswer in BaseQuizController.
type: 'POST',
async: false,
dataType: 'json',
data: {
"quizSessionQuestionId": quizSessionQuestionId,
"value": answer,
"numberOfHintsUsed": numberOfHintsUsed,
"markCompleteIfWrong": false
},
success: function (result) {
answerResult = result;
},
error: function (request, errorm) {
jAlert("Unable to record answer.", "An error occurred while saving this answer.");
return;
}
});
return answerResult;
};
While researching this, I found the following tutorial which indicates the pattern that I applied above (of assigning answerResult = result) is "CAUTION BROKEN CODE" because "A is for Asynchronous." :) http://jqfundamentals.com/chapter/ajax-deferreds
At any rate, please show me how to adjust the code above to use a deferred methodology, rather than the broken approach that I have so far. Thanks for your help.