表单成功提交后执行函数

时间:2021-02-03 11:50:12

标签: javascript ajax wordpress promise settimeout

我正在尝试通过添加另一个“步骤”来更改 WordPress 正在使用的注册程序。

由于我在我的数据库表中添加了外键约束,所以需要先填充 wp_users,然后执行其余代码。

我当前的 WordPress 表单提交中断代码是:

jQuery("#registerform").submit(function (e){
    e.preventDefault();
    let self = jQuery(this);
    self.unbind().submit();
    
    setTimeout(function(){
        if (jQuery("#registerusingwebauthn").is(":checked")) {

            let username = jQuery("#user_login").val();
            initializeCredentialType({
                authenticationMethod: "webauthn"
            });
            webauthn_registration(username,null)
                .then(function(e){
                    alert(e);})
                .catch(function (e){
                    console.log(e)});
        }
    },60000);

});

使用 self.unbind().submit(); 部分是因为必须先填写 wp_users 表,否则会发生违反约束的情况。

webauthn_registration 返回一个新的 Promise,其定义如下:

const webauthn_registration=(username,type)=>{
    return new Promise((resolve,reject)=>{
        // some variable definition here//
        if (username === ""){
            reject("Error: Username not given");
        }
        $.ajax({
            url: url,
            type: 'GET',
            data: {'username': username},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (error){reject(error);},
            success: function(serverregdata){
                // some variable definition here//
                navigator.credentials.create({publicKey: serverregdata})
                    .then(function(credentials){
                        // some variable definition here//
                        $.ajax({
                            url: url,
                            type: 'POST',
                            data: JSON.stringify(credentials),
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            error: function (error){alert(error);reject(error);},
                            success:function(success){alert(success);resolve('success');}
                        })
                    });
            }
        });
    });
}

问题在于 setTimeout() 不会等到 webauthn_registration 的承诺得到解决并在 webauthn_registration 完成之前重新加载页面。

有关更多信息(如果需要),AJAX 正在与 python 服务器交互,表约束如下:

wp_users.username 是 webauthn_users 的外键。 webauthn_users.id 是 webauthn_credentials 的外键。

附注 webauthn_registration 函数在提交函数直接链接到 webauthn_registration.

的静态 HTML 网站中运行良好

1 个答案:

答案 0 :(得分:0)

欢迎使用 stackoverflow。我建议尝试以下技巧:

$('form').one('submit', function(e) {
    e.preventDefault();
    // do your things ...

    // and when you done:
    $(this).submit();
});