2011-06-21 30 views
0

我有一個HTML多部分表單,名稱,電子郵件和文件上傳。JavaScript:表單提交前Ajax調用的控制邏輯?

我想先用Ajax註冊用戶。如果註冊成功,我想然後繼續提交表格。如果失敗,我想避免提交表格。

這是我的代碼:

--- HTML --- 
    <form id="account-form" method="post" enctype="multipart/form-data" data-ajax="false" action="upload.php" > 
    <input type="text" name="username" id="username" /> 
    <input type="email" name="email" id="email" /> 
    <input type="file" id="mediaupload" name="mediaupload" accept="image/*" /> 
    </form> 
    --- JavaScript --- 
    accountform.submit(function(event) { 
    var registration_ok = true; 
    // See if we can register the user 
    // And if we can, submit the form. 
    $.ajax({ 
     type: "POST", 
     url: "/usercreate.php", 
     data: postdata, 
     dataType: 'json', 
     success: function(data) { 
      // fine to submit the form. 
     }, 
     error: function (data){ 
      // If this fails, we don't want to submit the form! 
      registration_ok = false; 
     } 
    }); 
    return registration_ok; 
    }); 

然而,它總是返回true - 我想這是因爲主函數返回之前被稱爲Ajax的錯誤。

如何防止它在註冊失敗時返回true並提交表單?

謝謝!

回答

2

您需要返回false始終,而不是registation_ok,然後在成功的功能,進入:當您按下

document.forms["account-form"].submit(); //edited 

即從未提交表單提交按鈕,等待AJAX​​返回,然後只在註冊成功時才提交表單。

+0

啊我看到了 - 謝謝。好的解決方案:) – Richard

0

爲什麼不直接在您的.ajax語句的onSuccess處理程序中以編程方式提交表單?

事情是這樣的:

document.forms["account-form"].submit(); 
+0

因爲然後我得到一個無限循環... – Richard

+0

不,你不這樣做,如果你做得對。 – SBerg413

+0

我最初是這樣做的,並且一直重複調用'accountform.submit'函數。但是我從@ Ord的回答中看到,我應該將'false false'作爲默認值。 – Richard

0

你可以讓syncronic ajax調用,只需加上async:false,參數

+0

好,很好,解決了這個問題,謝謝! – Richard

0

對不起,我誤解了這個問題。在你的成功方法裏面觸發form.submit();

0

的問題是,AJAX調用是異步的,所以successerror函數不會被調用,直到函數返回後registration_ok值(你預先設置爲true)。

+0

是的,的確,這是問題:) – Richard