【问题标题】:AJAX form reloads my page :(AJAX 表单重新加载我的页面:(
【发布时间】:2017-07-13 13:15:50
【问题描述】:

我有一个 ajax 表单,可以从我的表单提交中读取数据。

我想让它在提交表单时显示来自我的 php 回调的响应。例如,如果用户输入密码,更新表并返回类似echo 'Successfully updated your password'; 我已尝试阅读有关如何执行此操作的不同帖子/博客,但我的错误不断发生。当我输入密码或个人资料图片后单击保存按钮时,它会不断刷新页面。

我的 HTML 表单代码:

<div class="modal fade -dark" id="ben2" data-animate-show="fadeInRight" data-animate-hide="fadeOutRight">
<div class="modal-dialog">
    <div class="modal-content -padded">
        <div class="modal-body _text-center">
            <form class="form-horizontal" enctype="multipart/form-data" id="myAccount" method="post" action="">

                <div class="form-group">
                    <label class="col-md-12 control-label" style="color: white; opacity: 100%;">Username</label>
                    <div class="col-md-12">
                        <input type="text" class="form-control" value="<?php foreach($users as $user) { echo $user[1]; } ?>" disabled>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-12 control-label" for="example-email" style="color: white; opacity: 100%;">Email</label>
                    <div class="col-md-12">
                        <input type="email" id="example-email" name="example-email" class="form-control" value="<?php foreach($users as $user) { echo $user[3]; } ?>" disabled>
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-12 control-label" style="color: white; opacity: 100%;">New Password</label>
                    <div class="col-md-12">
                        <input type="password" class="form-control default my-password required" name="securePassword_Val" id="form-element-colors-info" placeholder="Enter your new password here">
                    </div>
                </div>

                <div class="form-group">
                    <label class="col-md-12 control-label" style="color: white; opacity: 100%;">Profile Pic</label>
                    <div class="col-md-12">
                        <input class="form-control default profile-pic required" type="file" name="fileToUpload" id="form-elements-file">
                    </div>
                </div>
                <div class="form-group">
                    <label class="col-md-12 control-label" style="color: white; opacity: 100%;">User Level</label>
                    <div class="col-md-12">
                        <input type="text" class="form-control" value="<?php echo $member_config->userLevelValidation($con); ?>" disabled>
                    </div>
                </div>
        </div>

        <div class="col-sm-12">
            <div class="modal-footer _text-center _margin-bottom-none">
                <div class="btn-group">
                    <button class="btn -dark" data-dismiss="modal" aria-hidden="true" title="Close Without saving changes"><i class="fa fa-times"></i></button>
                    <button class="btn -dark" type="submit" name="SaveUserChanges" title="Save changes to your account"><i class="fa fa-save"></i></button>
                </div>
            </div>
            </form>
            <div id="myAccountResponse"></div>
        </div>
    </div>
</div>

如您所见,我有一个名为 myAccountResponse 的 div id,我希望在其中显示回调消息。

我的 AJAX 代码是:

<script>    
//JQuery Script to submit Form
$(document).ready(function () {
    $("#myAccount").validate({
        submitHandler : function () {
            // your function if, validate is success
            $.ajax({
                type : "POST",
                url : "includes/form_submit.php",
                data : $('#myAccount').serialize(),
                success : function (data) {
                    $('#myAccountResponse').html(data);
                }
                console.log('AJAX ERROR');
            });
        }
    });
});
</script>

我的 form_submit.php 代码:

    //Upload users image to our /uploads directory
    $uploaddir        = 'uploads/';
    $uploadfile       = $uploaddir . basename($_FILES['fileToUpload']['name']);
    $save_to_database = ("uploads/" . $_FILES["fileToUpload"]["name"]);
    $normalPassword   = mysqli_real_escape_string($con, $_POST["securePassword_Val"]);
    $pwd              = password_hash($normalPassword, PASSWORD_DEFAULT);
    $username         = $_SESSION["username"];

    //Run a list of checks so they don't have to type in a value if they don't want to change a current certain value

    if(isset($_POST['fileToUpload']) & isset($_POST['securePassword_Val'])) {
        if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) { echo 'Successfully uploaded image'; } else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
        $query = "UPDATE users SET password = '$pwd', profile_picture = '$save_to_database' WHERE username='$username'";
        $success['updatedAll'] = 'Successfully updated your password and profile picture!';
    }
    else if (empty($_POST['fileToUpload'])  & !empty($_POST['securePassword_Val'])) {
        $query = "UPDATE users SET password = '$pwd' WHERE username='$username'";
        $success['updatedPwd'] = 'Successfully updated your password!';
    }
    else if (empty($_POST['securePassword_Val']) & !(empty($_POST['fileToUpload']))) {
        if(move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) { echo 'Successfully uploaded image'; } else { die('Could not upload file.<br>Contact the Administrator of the website for more infomration.'); }
        $query = "UPDATE users SET profile_picture = '$save_to_database' WHERE username='$username'";
        $success['updatedPpic'] = 'Successfully updated your profile picture!';
    }
    else if (empty($_POST['securePassword_Val']) & empty($_POST['fileToUpload'])) {
        $errors['etyBoth'] = 'You must enter a value to change!';
    }

    if(count($errors) > 0) {
        if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&  strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
            echo $errors;
            exit;
        }

    } else {
        //Write our success return here
        echo $success;
        $result = mysqli_query($con, $query) or die('error');
    }

【问题讨论】:

  • 任何控制台错误?脚本是否在文档加载之前正确加载?
  • 我收到jQuery.Deferred exception: $(...).validate is not a function TypeError: $(...).validate is not a function
  • 这只是意味着您在使用它时没有加载验证插件。

标签: php ajax


【解决方案1】:

你应该阻止默认的表单处理,例如:

<script>    
//JQuery Script to submit Form
$(document).ready(function () {
    $("#myAccount").validate({
        submitHandler : function () {
            // your code

            return false; // Prevent default form handling
        }
    });
});
</script>

【讨论】:

    【解决方案2】:

    我认为您需要将return false; 放在您的 submitHandler 的末尾,告诉它不要进行正常的回发:

     submitHandler : function () {
                // your function if, validate is success
                $.ajax({
                    type : "POST",
                    url : "includes/form_submit.php",
                    data : $('#myAccount').serialize(),
                    success : function (data) {
                        $('#myAccountResponse').html(data);
                    }
                });
    
                return false; //prevent default postback
            }
    

    另外,console.log('AJAX ERROR'); 放错了位置,如果您检查控制台,可能会导致语法错误。如果要检查 ajax 错误,请根据 jQuery 文档包含“错误”回调选项。

    【讨论】:

    • 好的,但是使用&lt;button class="btn -dark" type="button" name="SaveUserChanges" title="Save changes to your account"&gt;&lt;i class="fa fa-save"&gt;&lt;/i&gt;&lt;/button&gt; 或&lt;button class="btn -dark" type="submit" name="SaveUserChanges" title="Save changes to your account"&gt;&lt;i class="fa fa-save"&gt;&lt;/i&gt;&lt;/button&gt; ?
    • 我认为你必须使用第二个,否则 jQuery validate 不会知道你已经提交了表单。 type="button" 按钮不会导致验证器正在等待的表单提交事件。
    • 检查您的浏览器控制台是否有任何其他错误。如果您遇到脚本错误,则不会运行任何验证或 ajax。
    • 我收到jQuery.Deferred exception: $(...).validate is not a function TypeError: $(...).validate is not a function
    • 听起来您实际上并未在页面中包含 jquery validate 插件文件。您应该在页面某处有一个&lt;script 引用,该引用调用 .js 文件进行 jQuery 验证。它是一个单独的插件,不是主 jQuery 库的一部分。确实,当您遇到 JavaScript 问题时,您应该首先检查控制台错误。
    【解决方案3】:

    为了防止页面刷新,您可以将事件处理程序附加到提交按钮的 onclick 事件。按钮应该有一个 id,它的类型应该从“提交”更改为“按钮”

    【讨论】:

    • 不,我知道为什么。这是因为我在我的主题中加载了另一个 js 文件,导致它没有在默认的 jquery 库中加载 AJAX。我认为我不能再在这个主题上使用 AJAX。
    猜你喜欢
    • 2013-02-06
    • 1970-01-01
    • 2023-04-11
    • 2018-12-03
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2018-02-24
    • 2012-08-06
    相关资源
    最近更新 更多