首页 > 解决方案 > 无法让 AJAX 提交工作以更新 post_content

问题描述

所以我在提交 AJAX 表单时遇到了一些问题,我似乎无法弄清楚为什么,下面我将解释我将要尝试提交表单的所有步骤。

脚本被排队 [WORKS]:确保加载包含 ajax 请求的文件。

function enqueue_scripts()
{
    if (!is_admin()) {
        wp_register_script('profile_edit_submit', content_url() . '/mu-plugins/fleishmanhillard/scripts/frontend-profile-edit.js', ['jquery'], '', true);
        wp_localize_script( 'profile_edit_submit', 'profile_edit', [
            // This will generate the admin URL that we can use on the front-end of our website
            'ajax_url' => admin_url('admin-ajax.php'),
            // Pass in a custom nonce name for JS
            'nonce' => wp_create_nonce('update_profile_validation'),
        ]);
        wp_enqueue_script('profile_edit_submit');
    }
}
add_action('wp_enqueue_scripts', 'enqueue_scripts');

这会更新帖子 ID 的 post_content [ WORKS ]:提交时,它会更新正确 ID 的数据库内容。

if (strtolower($_SERVER['REQUEST_METHOD']) === "post") {

    // @todo: Make sure that the account is associated with the logged in account on profile edits

    // If profile isn't empty, continue
    if (!empty($profile)) {

        // Grab the content submitted
        // @todo: Figure out how to set the $_POST request to a function
        $post_content = $_POST['content'];

        wp_update_post([
            'ID' => $profile->get_id(),
            'post_content' => $post_content,
        ]);
    }
}

HTML [作品]

<form action="" id="profile_update" method="POST">
    <input type="text" name="content" id="post_content" class="required">
    <input type="hidden" name="submitted" id="submitted" value="true" />
    <button type="submit"><?= 'Update Post' ?></button>
</form>

问题:所以提交工作,但它刷新提交页面,但我想继续提交 AJAX,但我不知道从哪里开始..这是我所拥有的,但它不能正常工作。

(function ($) {
    $(function($) {
        $('.profile_update').on('click', function() {
            $.ajax({
                type: 'POST',
                url: profile_edit.ajaxurl,
                data: {
                }
            });
        });
    });
})(jQuery);

当我提交表单时,它会更新数据库并将服务器请求从 GET 更改为 POST。

标签: javascriptphpjqueryajax

解决方案


我们必须更改 javascript。

(function ($) {
    $(function($) {
        $('#profile_update').on('submit', function(e) {
            $.ajax({
                type: 'POST',
                url: profile_edit.ajaxurl,
                data: $('#profile_update').serialize();
            });
            return false;
        });
    });
})(jQuery);

推荐阅读