Javascript Ajax php登录表单不直接指向其他页面

Javascript Ajax php登录表单不直接指向其他页面,javascript,php,jquery,html,ajax,Javascript,Php,Jquery,Html,Ajax,我在线学习了两个单独的Ajax教程,试图在出现错误消息时使我的登录表单不重定向到另一个页面。然而,这两种方法似乎都不起作用,我的表单仍然指向另一个页面并在那里显示错误消息。我不明白问题是什么,因为我几乎直接遵循了教程,它对他们有效,但对我无效。 以下是我的表格代码: <form id= "login_form" action="login.php" method="post"> <span id="login_errors"></span>

我在线学习了两个单独的Ajax教程,试图在出现错误消息时使我的登录表单不重定向到另一个页面。然而,这两种方法似乎都不起作用,我的表单仍然指向另一个页面并在那里显示错误消息。我不明白问题是什么,因为我几乎直接遵循了教程,它对他们有效,但对我无效。 以下是我的表格代码:

<form id= "login_form" action="login.php" method="post">
          <span id="login_errors"></span>
          <label>Email Address</label>
          <input type="text" name="email" id="email" required="required"/>
         <br />

         <label>Password</label>
         <input type="password" name="password" id="password" required="required"/>
         <br />

         <div class="checkbox">
         <input id="remember" type="checkbox" />
         <label for="remember">Keep me signed in</label>
         </div>

         <div class="action_btns">
         <div class="one_half last"><input type="submit" class="btn btn-blue" id="login_button" value="Login"></div>
         <div class="one_half last"><a href="#" id="register_form" class="btn">Sign up</a></div>
         </div>
</form>
以下是另一个教程的代码,该教程也不起作用:

$("#login_button").click(function(){
var action = $("#login_form").attr("action");
var form_data = {
    email: $("#email").val(),
    password: $("#password").val(),
    is_ajax: 1
};
$.ajax({
    type:"POST",
    url:"action",
    data: form_data,
    success: function(response){
        if(response == 'success'){
            $("#login_errors").html("successful!");
        }else{
            $("#login_errors").html("unsuccessful!");   
        }

    }
});
});
我已将Jquery包含在我的网页顶部:

<script type="text/javascript" src="jquery-1.11.0.min.js"></script>

并在页面顶部链接了我的ajax文件

<script type="text/javascript" src="login_Ajax.js"></script>

第二个ajax代码中有一个输入错误:url参数应该代替url:“action”,如下所示:

url: action,
不带引号,因为它引用了上面几行声明的变量。
不确定这是否解决了您的问题,但要了解整个情况,您还应该显示您的“login.php”。

对于您似乎忘记放置的第一个代码

第二秒钟,您似乎输入了无效的url

url:"action"
它应该是从你的HTML中提取出来的

url:"login.php"

你的问题的完整解决方案:因为你在学习一个教程,因为你在学习不同的教程和混合代码,让我给你一个简单的例子

不要忘记顶部的jquery库

<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
    <script>

因此将其复制到一个页面,例如login.php页面

<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script>
$(function(){


    $(document).on("click", ".ylogButton", function(e) {
    e.preventDefault();

//validate 
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
var emailp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

if (email=='')
{
    alert("Please enter your login email");
}

else if (password=='')
{
    alert("Please enter password");

}
else {  
        //Built a url to send
        var info = $("#yloginform").serialize();

        $.ajax({

            type: "POST",
            url: "authenticate.php",
            data: info,
            success: function(result){  
            $("#loginmsg").html(result);
                //$("#form")[0].reset();    
            }
        });
                e.preventDefault();

        }
    });

});

</script>

<div  id="loginmsg"></div>

<form class="form-signin"  id="yloginform">
        <h2  style="text-align:center;">  sign in </h2>
        <label for="inputEmail" class="sr-only">Login username</label>

        <input type="text" id="inputEmail" name="email" class="form-control" placeholder="login email" required autofocus>

        <label for="inputPassword" class="sr-only">Password</label>

        <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>

        <button class="ylogButton" type="submit">Sign in</button>
</form>
<?php 
//connection to db
$hostname_localhost = "localhost";
$database_localhost = "dbname"; //db name
$username_localhost = "root";
$password_localhost = ""; //db password if any
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR); 

?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>
<?php

if (isset($_POST["email"])) {

$email = $_POST['email'];
$password = $_POST['password'];            

}

//login registered user, but we always assume session has not been started 
if (!isset($_SESSION)) {
  session_start();
}


//this is just some magic
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['email'])) {
  $loginUsername=$_POST['email'];
  $password=$_POST['password'];
  $MM_fldUserAuthorization = "userlevel";
  $MM_redirectLoginSuccess = "$return_url";
  $MM_redirectLoginFailed = "$return_url";
  $MM_redirecttoReferrer = false;
  mysql_select_db($database_localhost, $localhost);

  $LoginRS__query=sprintf("SELECT email, password, userlevel FROM users WHERE email='$loginUsername' AND password='$password'"); 

  $LoginRS = mysql_query($LoginRS__query, $localhost) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {

    $loginStrGroup  = mysql_result($LoginRS,0,'userlevel');

    if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
    //declare two session variables and assign them
    $_SESSION['MM_Username_check'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;       

    if (isset($_SESSION['PrevUrl']) && false) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];  
    }

    echo "welcome, $lastname ";
    $redirectpage = "sucesspage.php";   
    echo "<script>window.location.href='$redirectpage';</script>";

    }
    else {
    echo "wrong username or password";
    }
}
    else
    {
        $text = "Error! Please try again.";
    }

?>

$(函数(){
$(文档).on(“单击”,“.ylogButton”,函数(e){
e、 预防默认值();
//证实
var email=$(“#inputEmail”).val();
var password=$(“#inputPassword”).val();
var emailp=/^\w+([\.-]?\w+*@\w+([\.-]?\w+*(\.\w{2,3})+$/;
如果(电子邮件=“”)
{
警报(“请输入您的登录电子邮件”);
}
else if(密码=“”)
{
警报(“请输入密码”);
}
否则{
//构建了一个要发送的url
var info=$(“#yloginform”).serialize();
$.ajax({
类型:“POST”,
url:“authenticate.php”,
数据:信息,
成功:函数(结果){
$(“#loginmsg”).html(结果);
//$(“#形式”)[0]。重置();
}
});
e、 预防默认值();
}
});
});
登录
登录用户名
密码
登录
然后打开另一个名为authenticate.php的文件并复制此登录php代码

<script type="text/javascript" src="jquery-1.11.0.min.js"></script>
<script>
$(function(){


    $(document).on("click", ".ylogButton", function(e) {
    e.preventDefault();

//validate 
var email = $("#inputEmail").val();
var password = $("#inputPassword").val();
var emailp = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;

if (email=='')
{
    alert("Please enter your login email");
}

else if (password=='')
{
    alert("Please enter password");

}
else {  
        //Built a url to send
        var info = $("#yloginform").serialize();

        $.ajax({

            type: "POST",
            url: "authenticate.php",
            data: info,
            success: function(result){  
            $("#loginmsg").html(result);
                //$("#form")[0].reset();    
            }
        });
                e.preventDefault();

        }
    });

});

</script>

<div  id="loginmsg"></div>

<form class="form-signin"  id="yloginform">
        <h2  style="text-align:center;">  sign in </h2>
        <label for="inputEmail" class="sr-only">Login username</label>

        <input type="text" id="inputEmail" name="email" class="form-control" placeholder="login email" required autofocus>

        <label for="inputPassword" class="sr-only">Password</label>

        <input type="password" name="password" id="inputPassword" class="form-control" placeholder="Password" required>

        <button class="ylogButton" type="submit">Sign in</button>
</form>
<?php 
//connection to db
$hostname_localhost = "localhost";
$database_localhost = "dbname"; //db name
$username_localhost = "root";
$password_localhost = ""; //db password if any
$localhost = mysql_pconnect($hostname_localhost, $username_localhost, $password_localhost) or trigger_error(mysql_error(),E_USER_ERROR); 

?>
<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
?>
<?php

if (isset($_POST["email"])) {

$email = $_POST['email'];
$password = $_POST['password'];            

}

//login registered user, but we always assume session has not been started 
if (!isset($_SESSION)) {
  session_start();
}


//this is just some magic
$loginFormAction = $_SERVER['PHP_SELF'];
if (isset($_GET['accesscheck'])) {
  $_SESSION['PrevUrl'] = $_GET['accesscheck'];
}

if (isset($_POST['email'])) {
  $loginUsername=$_POST['email'];
  $password=$_POST['password'];
  $MM_fldUserAuthorization = "userlevel";
  $MM_redirectLoginSuccess = "$return_url";
  $MM_redirectLoginFailed = "$return_url";
  $MM_redirecttoReferrer = false;
  mysql_select_db($database_localhost, $localhost);

  $LoginRS__query=sprintf("SELECT email, password, userlevel FROM users WHERE email='$loginUsername' AND password='$password'"); 

  $LoginRS = mysql_query($LoginRS__query, $localhost) or die(mysql_error());
  $loginFoundUser = mysql_num_rows($LoginRS);
  if ($loginFoundUser) {

    $loginStrGroup  = mysql_result($LoginRS,0,'userlevel');

    if (PHP_VERSION >= 5.1) {session_regenerate_id(true);} else {session_regenerate_id();}
    //declare two session variables and assign them
    $_SESSION['MM_Username_check'] = $loginUsername;
    $_SESSION['MM_UserGroup'] = $loginStrGroup;       

    if (isset($_SESSION['PrevUrl']) && false) {
      $MM_redirectLoginSuccess = $_SESSION['PrevUrl'];  
    }

    echo "welcome, $lastname ";
    $redirectpage = "sucesspage.php";   
    echo "<script>window.location.href='$redirectpage';</script>";

    }
    else {
    echo "wrong username or password";
    }
}
    else
    {
        $text = "Error! Please try again.";
    }

?>

这将是登录用户的电子邮件

登录成功后,您将被重定向到
successpage.php