Tomas
Tomas

Reputation: 2726

jQuery ajax returns

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 I'm 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.

Upvotes: 1

Views: 110

Answers (1)

guanxiaohua2k6
guanxiaohua2k6

Reputation: 371

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;
}

Upvotes: 1

Related Questions