Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use timeout attribute with post method in jQuery ajax request?

I've a following function:

function mark_unmark_user_answer(targ, answer, answer_id, test_id, test_type, question_no, module_url) {
    if(checked==targ){
    targ.checked=false;
    checked=false;
  } else {
    checked=targ;
  }

    $.post(module_url, {'test_id':test_id, 'question_no':question_no, 'op':'mark_ans', 'test_type':test_type, 'answer_no':answer, 'answer_id':answer_id}, function(data) { 
        if(jQuery.trim(data)=='unmark_ans') {
          $('input[type="radio"]').removeAttr('checked');
          $('#display_'+question_no).removeClass('green');
          $('#display_'+question_no).removeClass('blue');
          $('#display_'+question_no).addClass('orange');
        } else {
            //$('#mark_review').val('Mark'); 
            $('#display_'+question_no).removeClass('orange');
            $('#display_'+question_no).removeClass('blue');
            $('#display_'+question_no).addClass("green");
            $('#mark_review').attr('disabled', false);  
        }
        var total_questions = $('#total_questions').val();
        test_question_attempted_count( total_questions );    
    });
}

I want to assign time-out of 30 seconds to this function. So if the response for the ajax request is not received within 30 seconds then the alert message saying that "Your internet connection has some problem" should appear. Otherwise normal function should get execute.

Can anyone help on this?

Thanks in advance.

like image 387
PHPLover Avatar asked Feb 14 '14 05:02

PHPLover


1 Answers

Try use

$.ajax({
    type: "POST",
    url: your_url_request,
    data: {field: value, field_2: value_2},    
    timeout: 1000,
    error: function(jqXHR, textStatus, errorThrown) {
        if(textStatus==="timeout") {
           //do something on timeout
        } 
    }});

You can has more information in: http://api.jquery.com/jQuery.ajax/

like image 89
Santos L. Victor Avatar answered Oct 25 '22 03:10

Santos L. Victor