简体   繁体   English

如何在AJAX通话后继续提交表单?

[英]How to continue form submission after an AJAX call?

I want to validate user entries on a WordPress post upon hitting the submit button, display an error message is there are problems, and submit the form if everything is OK. 我想在点击提交按钮时验证WordPress帖子上的用户条目,显示有问题的错误消息,如果一切正常,则提交表单。 I have a PHP function that does the checking, returning true if data in form_data is OK, some error code otherwise. 我有一个PHP函数来执行检查,如果form_data数据form_data则返回true否则返回一些错误代码。 The following JavaScript issues the AJAX request, and was supposed to continue submitting the form upon successful checking, but it doesn't: 以下JavaScript发布了AJAX请求,并且应该在成功检查后继续提交表单,但它不会:

        jQuery(document).ready(function() {
            jQuery('#post').submit(function() {

                var form_data = jQuery('#post').serializeArray();
                var data = {
                    action: 'ep_pre_submit_validation',
                    security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
                    form_data: jQuery.param(form_data),
                };
                var proceed = false;
                jQuery.post(ajaxurl, data, function(response) {
                    if (response.indexOf('true') > -1 || response == true) {
                        proceed = true;
                    } else {
                        alert("Error: " + response);
                        proceed = false;
                    }
                });
                jQuery('#ajax-loading').hide();
                jQuery('#publish').removeClass('button-primary-disabled');
                return proceed; //breakpoint here makes the code run
            });
        });

The code is adapted from a WPSE question , which originally didn't work for me as the form didn't get submitted. 该代码改编自WPSE问题 ,该问题最初对我不起作用,因为表单未提交。 I found out that if the jQuery function bound to .submit() returns true, the form should be submitted, so that's what I tried to implement. 我发现如果绑定到.submit()的jQuery函数返回true,那么应该提交表单,这就是我试图实现的。 With the code above, it doesn't seem to work at first (form doesn't get submitted when there are no errors), but upon close inspection with Firebug proceed seems to get the right result if a breakpoint is inserted at the return proceed line. 使用上面的代码,它似乎一开始就不起作用(当没有错误时表单不会被提交),但是在使用Firebug proceed仔细检查后,如果在return proceed插入断点,则似乎得到了正确的结果线。 It works as intended with valid data only if I wait it out a bit upon hitting the breakpoint, and then continue execution. 只有在我遇到断点时稍稍等了一下,然后继续执行它才能按预期使用有效数据。 If there are errors, the alert is issued without a problem. 如果有错误,则会发出警报而不会出现问题。

What is the best way to handle this? 处理这个问题的最佳方法是什么?

EDIT 编辑

Based on @Linus answer below, the following code works with both valid and invalid data: 根据下面的@Linus答案,以下代码适用于有效和无效数据:

        jQuery(document).ready(function() {
            jQuery('#post').submit(function() {
                if(jQuery(this).data("valid")) {
                    return true;
                }

                var form_data = jQuery('#post').serializeArray();
                var data = {
                    action: 'ep_pre_submit_validation',
                    security: '<?php echo wp_create_nonce( 'pre_publish_validation' ); ?>',
                    form_data: jQuery.param(form_data),
                };
                jQuery.post(ajaxurl, data, function(response) {
                    if (response.indexOf('true') > -1 || response == true) {
                        jQuery("#post").data("valid", true).submit();
                    } else {
                        alert("Error: " + response);
                        jQuery("#post").data("valid", false);

                    }
                    //hide loading icon, return Publish button to normal
                    jQuery('#ajax-loading').hide();
                    jQuery('#publish').removeClass('button-primary-disabled');
                });
                return false;
            });
        });

Bind your button to a validation function instead of submit. 将您的按钮绑定到验证功能而不是提交。 If it passes validation, call submit(). 如果它通过验证,请调用submit()。

Short answer: You can't - not in this manner. 简短回答:你不能 - 不是这样。

Some background: The callbacks you supply as arguments to functions such as $.post are executed asynchronously. 一些背景:作为$.post等函数的参数提供的回调是异步执行的。 This means that you will return proceed before your success callback has been executed, and proceed will always be false . 这意味着您将在执行成功回调之前 return proceed ,并且proceed将始终为false With your breakpoint, if you wait until the success callback has executed, proceed will be true and all will be well. 使用断点,如果等到成功回调已执行,则proceed将为true ,一切都会正常。

So, if you want to submit the form after your ajax request has finished, you must submit it using javascript. 因此,如果您想在ajax请求完成后提交表单,则必须使用javascript提交。 This is pretty easy with jQuery, just do a jQuery $.post with data: $("yourForm").serialize() and url: yourForm.action . 使用jQuery非常简单,只需使用data: $("yourForm").serialize()执行jQuery $.post data: $("yourForm").serialize()url: yourForm.action

This is basically what you already are doing, you just have to repeat that call to the URL to which you actually want to post the data. 这基本上就是您已经在做的事情,您只需要重复调​​用您实际想要发布数据的URL。

EDIT: 编辑:

Another way would be to set an attribute on your form, say valid , and in your submit handler check that: 另一种方法是在表单上设置一个属性,比如说valid ,并在submit处理程序中检查:

jQuery("#post").submit(function() {
    if($(this).data("valid")) {
        return true;
    }
    // Rest of your code
});

And in the success callback for your validation ajax request you would set/clear that attribute, and then submit: 在验证ajax请求的成功回调中,您将设置/清除该属性,然后提交:

$("#post").data("valid", true).submit();

EDIT: 编辑:

You also want to do your "ajax-loading"/button enabling inside the callback for $.post for the same reasons stated above - as it is, they will happen immediately, before your ajax call returns. 出于上述相同的原因,您还希望在$.post的回调中启用“ajax-loading”/按钮,因为它们会在您的ajax调用返回之前立即发生。

Wordpress has its own mechanism to process Ajax requests, using wp-admin/wp-ajax.php. Wordpress有自己的机制来处理Ajax请求,使用wp-admin / wp-ajax.php。 This allows you to run arbitrary code on either side of the Ajax boundary without having to write the back and forth status-checking code and all that. 这允许您在Ajax边界的任何一侧运行任意代码,而无需编写来回状态检查代码以及所有这些代码。 Set up your callbacks and go.... 设置你的回调并去....

The real question is - why are you doing validation server-side? 真正的问题是 - 你为什么要在验证服务器端? Why can't you load in the validation criteria before - as the post is being written? 为什么你不能在之前加载验证标准 - 因为正在撰写帖子? Then your validation can happen real-time and not on-submit. 然后您的验证可以实时发生,而不是提交。

jquery.post is performed asynchronously, which means the JS will continue before it gets the reply. jquery.post是异步执行的,这意味着JS会在收到回复之前继续。 You're stuck with Diodeus's answer - bind the button to validtion which then submits the form (which makes it not degrade well), or change your $.post to ajax and turn off async, which will force it to wait for response before proceeding...possibly locking up JS on your page until it times out. 你坚持使用Diodeus的答案 - 将按钮绑定到验证然后提交表单(这使得它不会降级),或者将$ .post更改为ajax并关闭异步,这将迫使它等待响应然后继续...可能会锁定页面上的JS,直到超时为止。

$.ajax({
    type: 'POST',
    url: ajaxurl,
    async:false,
    data: data,
    timeout:3000,
    success: function(){

    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM