简体   繁体   中英

Ajax php login form to not direct to another page

I have followed two seperate Ajax tutorials online to try and make my login form not redirect to another page when there are error messages. However, neither of the methods seem to be working and my form still directs to another page and shows the error messages there. I don't understand what the problem is as I have pretty much followed the tutorials directly and it works for them but not me. Below is the code for my form:

<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>

and here is the ajax code based on one of the tutorials I follwed:

$("#login_button").click(function(){

$.post($("#login_form").attr("action"), $("#login_form:input").serializeArray(), function(info){$("#login_errors").html(info);});
});

$("login_form").submit(function(){
    return false;
});

here is the code for the other tutorial that also didn't work:

$("#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!");   
        }

    }
});
});

I have included Jquery at the top of my webpage:

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

and also linked my ajax file beneath that too at the top of the page.

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

There is a typo in the second ajax code: the url parameter should instead of url: "action", look like this:

url: action,

without quotes, as it refers to the variable declared a few lines above. Not sure if this solves your problem, but to see the whole picture you should also show your "login.php".

for the first code you seems to have forgotten to put #

$("#login_form").submit(function(){
    return false;
});

for second you seems to have entered invalid url

url:"action"

it should be jugging from your HTML

url:"login.php"

Complete solution to your problem: Since you were following a tutorial since you were following different tutorials and mixing codes, Let me give you a freash and simple one;

Dont forget the jquery library at the top eg

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

So copy this to a page eg login.php page

<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>

Then open another file called authenticate.php and copy this login php code

<?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.";
    }

?>

Then ensure in your database you have

  1. columns email , password and userlevel

The above code will generate session variable <?php $_SESSION['MM_Username_check'] ?> that will be the email of a logged in user.

And when your login is successful you will be redirected to successpage.php

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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