我的jQuery AJAX表单提交还在刷新页面吗?

时间:2019-02-20 作者:Rollor

我设法将Wordpress jQuery连接正确。所有内容都按预期插入到数据库中,但出于某种原因,it is still refreshing the whole page?

php/html (Wordpress Page Template):

<?php
if(isset($_POST[\'send\']))
{
   send_projectmessage($projectid, $userid, $projectmessage);
}
?>
<html>
<body>
<div id="messages">
<?php 
$messages = load_projectmessages($projectid);
        foreach ($messages as $message) { /*echo the messages and put in a nice div*/ }
?>
</div>
<form id="form-pm" method="post" enctype="multipart/form-data" action="">
            <textarea name="projectMessage" rows=3 id="project-message"></textarea>

            <input type="submit" name="send" value="send message">
</form>

JS:

$(\'#form-pm\').on(\'send\', function(e) {

        e.preventDefault();

        var ajaxRequest =
        $.ajax({
            url: admin_ajax.ajax_url,
            type: \'post\',
            data: { 
                action: \'send_projectmessage\',
                projectid: \'projectid\',
                userid: \'userid\',
                projectmessage: \'projectmessage\'
                }, 
            contentType: \'application/json; charset=utf-8\',
            dataType: \'json\' });

        ajaxRequest.done(function() { } );
        ajaxRequest.fail(function(jqXHR) { alert(\'You are fail. \' + jqXHR); } );

        return false;
    });

functions.php

function send_projectmessage($projectid, $userid, $message) {
    global $wpdb;
    $wpdb->insert(\'tbl_messages\', array(
        \'project_id\' => $projectid,
        \'user_id\' => $userid,
        \'message_body\' => $message
    ));
    return false;
    wp_die();
}
add_action(\'wp_ajax_send_projectmessage\', \'send_projectmessage\');
我有e.preventDefault(); 还有return false. 我的消息被正确地插入MySql表,但整个页面仍然会重新加载!

1 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

您使用了错误的js事件。使用以下代码注册回调:

$(\'#form-pm\').on(\'send\', function(e) {
但没有调用任何事件send 在窗体上。应该是这样的submit. 下面是该行的固定版本:

$(\'#form-pm\').on(\'submit\', function(e) {