从脚本更新响应div

时间:2015-04-17 18:22:19

标签: javascript php jquery ajax

这里没有什么比我的需要更合适了。我确信这与大多数事情相比都很容易,但我真的对jQuery没有任何了解或理解,所以我在这里有点啰嗦。

我有一个密码更改表单(目前可以修改密码),但它没有做的是表明发生了任何事情。所以现在当我填写密码时,点击提交,表单被提交到changePassword.php脚本,并正确处理,但我没有看到这个。

我想要清除密码表单,并在按钮下面的div填充我的一条$ response消息。

main.php

<div id="s-window">
   <form id="changepassword" action="changePassword.php" method="POST">
    <input type="password" name="currentPassword" placeholder="Current Password"/>
    <input type="password" name="newPassword" placeholder="New Password"/>
    <input type="password" name="confirmPassword" placeholder="Confirm Password"/>
    <input class="button" type="submit" value="Change Password" />
   </form>
<div id="response"></div>

main.php中的jQuery:

$(document).ready(function(){
    $("#changepassword").submit(function(e) {
        e.preventDefault(); // stop normal form submission
        $.ajax({
            url: "changePassword.php",
            type: "POST",
            data: $(this).serialize(), // you also need to send the form data
            dataType: "html",
            success: function(data){ // this happens after we get results
                $("#results").show();
                $("#results").append(data);
            }
        });
    });
});

最后,脚本changePassword.php

$currentPassword = ($_POST['currentPassword']); 
$password = ($_POST['newPassword']);
$password2 = ($_POST['confirmPassword']);
$username = ($_SESSION['username']);
$response = '';

if($password === '' || $password === FALSE){
  $response = "Your password cannot be blank!";
} else {
  if(strlen($password)<7){
    $response = "Your password is too short!";
  } else {
    if ($password <> $password2) { 
      $response = "Your passwords do not match.";
    }
    else if ($password === $password2){

    $hashed_password = password_hash($password, PASSWORD_DEFAULT);


    $sql = "UPDATE Staff SET password='$hashed_password' WHERE username='$username'";

    mysql_query($sql) or die( mysql_error() );
    echo $response;
    }
    else { mysqli_error($con); }
  };
};

2 个答案:

答案 0 :(得分:1)

您的$response变量仅在嵌套的else语句中返回。无论这些块中发生了什么,都可以将return $response移动到if \ else语句的外部,而不管这些块中发生了什么。

另外,填充结果的div的ID为response,但您尝试将其附加到ID为div的{​​{1}}。

更改

results

$("#results").show();
$("#results").append(data);

如果这不起作用,请尝试$("#response").show(); $("#response").append(data); 以确保您实际上从服务器获得响应。使用浏览器开发人员工具查看日志。

希望这有帮助!

答案 1 :(得分:1)

我更新了你的编码。根据@ jay-blanchard的建议,我用PDO更新了changePassword.php代码。

并且还实现了验证规则并将它们存储在数组中。在之前的代码中,您使用了if else if。因此,如果密码有3个错误,则表示它不会同时显示。您需要按3次提交按钮才能逐个获取这些错误。现在我更新了那些将这些错误存储到数组中的内容,在最后阶段我将它们编码为json。检查以下代码。如果您发现任何问题,请回复我。因为,我还没有测试过代码。希望它能成功执行。

  

changePassword.php

<?php

// Database configuration
define('DB_HOST', 'localhost');
define('DB_USER', 'username');
define('DB_PASS', 'password');
define('DB_NAME', 'database');

// Initializing error array
$response['error'] = array();

try {
    $db = new PDO('mysql:host=' . DB_HOST .';dbname=' . DB_NAME . ';charset=utf8mb4', DB_USER, DB_PASS);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
} catch (Exception $e) {
    $response['error'][] = "Error in DB Connection";
}

// Store post and session values to variable.
$currentPassword = $_POST['currentPassword']; 
$password = $_POST['newPassword'];
$password2 = $_POST['confirmPassword'];
$username = $_SESSION['username'];

// Validating Password
if($password === '' || $password === FALSE ){
    $response['error'][] = "Your Password cannot be blank";
}
if(strlen($password)<7){
    $response['error'][] = "Your Password is too short!";
}
if($password <> $password2){
    $response['error'][] = "Your Passwords do not match";
}

// If validation password update the password for the user.
if(empty($response['error'])){
    $stmt = $db->prepare('UPDATE Staff SET password=? WHERE username=?'); // Prepare the query
    $stmt->execute(array(password_hash($password, PASSWORD_DEFAULT), $username)); // Bind the parameters to the query
    $affectedRows = $stmt->rowCount(); // Getting affected rows count
    if($affectedRows != 1){
        $response['error'][] = "No User is related to the Username";
    }
}

// printing response.
if(!empty($response['error'])){
    echo json_encode($response);
}else{
    echo json_encode(array("success"=>true));
}

我将响应格式化为json。因此,我将ajax函数dataType更新为json。请检查以下代码。

  

main.php

<div id="s-window">
    <form id="changepassword" action="changePassword.php" method="POST">
        <input type="password" name="currentPassword" placeholder="Current Password"/>
        <input type="password" name="newPassword" placeholder="New Password"/>
        <input type="password" name="confirmPassword" placeholder="Confirm Password"/>
        <input class="button" type="submit" value="Change Password" />
    </form>
<div id="response" style="display:none"></div>

<script>
$(document).ready(function(){
    $("#changepassword").submit(function(e) {
        e.preventDefault(); // stop normal form submission
        $.ajax({
            url: "changePassword.php",
            type: "POST",
            data: $(this).serialize(), // you also need to send the form data
            dataType: "json",
            success: function(data){ // this happens after we get results
                $("#response").show();
                $("#response").html("");
                // If there is no error the response will be {"success":true}
                // If there is any error means the response will be {"error":["1":"error",..]}
                if(data.success){
                    $("#response").html("Successfully Updated the Password");
                }else{
                    $.each(data.error, function(index, val){
                        $("#response").append(val+"<br/>");
                    });
                }
            }
        });
    });
});
</script>

希望它会对你有所帮助。享受。