登录表单失败jQuery+Ajax+PHP



我试图在Ajax脚本中成功登录后刷新页面,但页面没有刷新。我被迫手动刷新页面,只有这样它才会显示为已登录。提前感谢您的帮助,非常感谢。

这是ajax的登录脚本;

$("document").ready(function() {
    $("#what").click(function() {
        var email = $("#emailLogin").val();
        var password = $("#passwordLogin").val();
        var dataString = 'email='+email+'&password='+password;
        $.ajax({
            type: "POST",
            url: "authenticate.php",
            data: dataString,
            success: function(response){                
                //alert (response);
                if (response == 0) {
                $("#problem").html("Please enter correct details");
                            } else {
                    window.location = "index.php";
                }
            }
        });
    return false;
    });
});

这是用于验证表单的php脚本

// authenticate.php
session_start();
require_once "database.php";
db_connect();
require_once "auth.php";

$user_id = credentials_valid($_POST['email'], $_POST['password']);
if($user_id){
  log_in($user_id);
  if($_SESSION['redirect_to']){
    header("Location: " . $_SESSION['redirect_to']);
    unset($_SESSION['redirect_to']);
  }else{
    header("Location: index.php");
  }
}else{
  echo "0";
}
?>

当然需要刷新页面,因为您使用JQuery发布,php函数只返回一些数据。

你有两个选择:

  1. 张贴经典方式(表单提交)

  2. 使用window.location='url'从javascript重定向;

您可以使用javascript重定向。AJAX请求无法重定向用户的浏览器

if (response == 0) {
    $("#problem").html("Please enter correct details");
} else {
    window.location = "/index.php";
}

如果响应不等于0,我会在js中重定向,如果登录失败,在php中重定向。服务器端重定向也不适用于ajax,您必须使用window.location.href = 'url'重定向它。您也可以在响应中发送代码状态,但不能自己编写。

最新更新