简体   繁体   English

AJAX表单重新加载我的页面:(

[英]AJAX form reloads my page :(

I have a an ajax form that reads the data from my form submit. 我有一个ajax表单,可从表单提交中读取数据。

I want to make it so when the form is submitted, it shows the response from my php callback. 我想这样做,以便在提交表单时显示来自我的php回调的响应。 For example, if the user entered in the password, update the table and return something like echo 'Successfully updated your password'; 例如,如果用户输入了密码,则更新表并返回类似echo 'Successfully updated your password'; update echo 'Successfully updated your password'; I have tried reading different posts / blogs about how to do this but my error keeps occuring. 我尝试阅读有关如何执行此操作的不同文章/博客,但我的错误不断发生。 It keeps refreshing the page when I click the save button after entering either the password or the profile picture. 输入密码或个人资料图片后,单击“保存”按钮,它将不断刷新页面。

My HTML Form code : 我的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>

As you can see, I have a div id called myAccountResponse which I want the callback message to display in. 如您所见,我有一个名为myAccountResponse的div ID,希望在其中显示回调消息。

My AJAX code is : 我的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>

My form_submit.php code : 我的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');
    }

You should prevent default form handling, for example: 您应该防止默认表单处理,例如:

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

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

I think you need to put return false; 我认为您需要将return false;设为return false; at the end of your submitHandler, to tell it not to do a normal postback: 在您的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
        }

Also console.log('AJAX ERROR'); 也是console.log('AJAX ERROR'); was in the wrong place and probably causing a syntax error if you checked your console. 放在错误的位置,如果您检查控制台,可能会导致语法错误。 If you want to check for ajax errors, include an "error" callback option as per the jQuery documentation. 如果要检查ajax错误,请根据jQuery文档添加“错误”回调选项。

To prevent the page from refreshing, you can attach the event handler to the submit button's onclick event. 为了防止页面刷新,可以将事件处理程序附加到提交按钮的onclick事件上。 The button should be given an id and its type should be change from 'submit' to 'button' 应该给按钮一个id,其类型应该从“提交”更改为“按钮”

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

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