2016-01-28 83 views
2

我有一個表單和提交。如果有東西被填充,提交之前我想確保它的價值(用ajax),如果是,那麼我只能讓它繼續。所以,如何在AJAX事件結束之前暫停提交事件?

$('#contact').submit(function() { 
    // ajax 
    $.ajax({ 
    type: 'POST', 
    url: $(this).attr('ajaxgetaccommodationsbyemail'), 
    success: function(answer) { 
     here a popup window opens, which waits until I press YES or NO 
    }, 
    async: false 
    }); 

    this is when return TRUE or FALSE 
    there should be something like 
    do while (popupWindowClosed) 
    so $.when is not an option 

}); 
+1

AJAX成功返回時設置全局變量。如果未設置全局變量,則取消'submit'事件。 – Blazemonger

回答

6

您可以防止使用jQuery提交,然後實際調用本機提交發送表單

$('#contact').on('submit', function(e) { 

    e.preventDefault(); 

    var form = this; 

    $.ajax({ 
     type: 'POST', 
     url: $(this).attr('ajaxgetaccommodationsbyemail'), 
     success: function(answer) { 
      popup(function(yesorno) { 

       if (yesorno) { 
        form.submit(); 
       } 

      }); 
     } 
    }); 
}); 

而且async:false刪除,因爲你應該從未做syncronous阿賈克斯。

+0

,但「如果(確認('你確定')){」不是那樣的。它的另一個「異步」的東西 –

+2

無關緊要,同樣的原則適用,你在'success'函數內添加彈出窗口,如果它是一個自定義彈出窗口,它有一個回調函數,你可以在其中調用'submit()',我將編輯答案回到最初的 – adeneo

+0

,但是。提交時,默認行爲被禁用。當我調用form.submit()時,它將再次禁用默認行爲.... –

1
$('#contact').submit(function(e) { 
    e.preventDefault(); 
    var form = $(this); 
    // ajax 
    $.ajax({ 
    type: 'POST', 
    url: $(this).attr('ajaxgetaccommodationsbyemail'), 
    success: function(answer) { 
     $.dialog(function(){ // this line is "pseudocode", put the code of your dialog here. 
      // when clicked YES 
      form.submit(); 
     }, function(){ 
      // when clicked NO 
     }); 
    } 
    }); 
}); 

如果你真的想要一個自定義對話框,您可以使用:https://jqueryui.com/dialog/#modal-confirmation

1

jQuery的阿賈克斯錯誤和成功的回調。您可以執行以下操作:

$('#contact').submit(function() { 
    // ajax 
    $.ajax({ 
    type: 'POST', 
    url: $(this).attr('ajaxgetaccommodationsbyemail'), 
    error: function (request, error) { 
     // there was error. handle it how you want 
    }, 
    success: function() { 
     // open your pop up window 
     // and do other stuff 
    } 
    }); 

});