I think this will be some obvious problem, but I cannot figure it out. I hope someone can help me.
So I have a slider with 3 slides - Intro, Question, Submit
Now I want to make sure that if the question is answered wrong people cannot slide to Submit.
The function to move slide is like this:
function changeSlide(slide){
// In case current slide is question check the answer
if (jQuery('.modalSteps li.current',base).hasClass('questionStep')){
checkAnswer(jQuery('input[name="question_id"]',base).val(), jQuery('input[name="answer"]:checked',base).val());
}
jQuery('.modalSteps li.current',base).fadeOut('fast',function(){
jQuery(this).removeClass('current');
jQuery(slide).fadeIn('fast',function(){
jQuery(slide).addClass('current');
});
});
// In case the new slide is question, load the question
if (jQuery(slide).hasClass('questionStep')){
var country = jQuery('input[name="country"]:checked',base).val();
loadQuestion(country);
}
}
Now as you can see on first lines, I am calling function checkAnswer, which takes id of question and id of answer and pass it to the AJAX call.
function checkAnswer(question, answer){
jQuery.ajax({
url: window.base_url+'ajax/check_answer/'+question+'/'+answer+'/',
success: function(data){
if (!data.success){
jQuery('.question',base).html(data.message);
}
}
});
}
The problem i am having is that I cannot say
if(checkAnswer(...)){}
Because of Ajax it always returns false or undefined. What I need is something like this:
function changeSlide(slide){
// In case current slide is question check the answer
if (jQuery('.modalSteps li.current',base).hasClass('questionStep')){
if (!checkAnswer(jQuery('input[name="question_id"]',base).val(), jQuery('input[name="answer"]:checked',base).val())){
return false;
}
}
...
So it will prevent the slide from moving on.
Now when Im thinking about it, I will probably have slide like "Wrong answer" so I could just move the slide there, but I would like to see the first solution anyway.
Thank you for tips
You can set option async of ajax to false to wait for the reply from server. Therefore, the code may be like the below.
function checkAnswer(question, answer){
result = false;
jQuery.ajax({
async: false,
url: window.base_url+'ajax/check_answer/'+question+'/'+answer+'/',
success: function(data){
result = data.success
if (!data.success){
jQuery('.question',base).html(data.message);
}
}
});
return result;
}