如何在成功的ajax调用上重定向用户? 否则在表单中显示错误消息

问题描述:

Updated: Thanks for reading - My login form calls on login.php to check whether the user has entered a registered email address or not. If the address is registered, it echoes back "redirect", if it is not registered, it echoes "Email not registered". My current code only redirects to mydomain.com/# since the form action is set to #, because I'm using the ajax to submit the form.

How do I:

Redirect the user to page private.php if the php has echoed "redirect" - otherwise how do I display "Email not registered" within the form, if it echoes "Email not registered"? My login form contains a div to display the error if necessary.

ajax:

 <script>
    $(document).ready(function() {

$("#loginform").submit(function(e){
    e.preventDefault();
    $.post('login/login.php', {email: $('#email').val(), loginsubmit: 'yes'}, function(data)
    {
    if (data === "redirect") 
{ 
window.location = "http://www.gathercat.com/login/private.php"; 
} 

else {  
 $("#formResponse").html(data).fadeIn('100');
        $('#email').val(''); 
    }
, 'text');
    return false;
    }
});
});
</script>

PHP:

...
    if($login_ok) 
            { 
               echo 'redirect';
            } 
            else 
            { 
                echo 'That email address is not registered';            
            } 
...

login form:

...
 <form id="loginform" name="loginform" method="POST" class="login" action="#">
    <input name="email" id="email" type="email" class="feedback-input" placeholder="My Email" required/>
     <div id="formResponse" style="display: none;"></div>
     <button type="submit" name="loginsubmit" class="loginbutton">Login</button>
...

Full PHP

<?php
$emailaddress = $_POST["email"];
?>
<?php 

    // First we execute our common code to connection to the database and start the session 
    require("common.php"); 

    // This if statement checks to determine whether the login form has been submitted 
    // If it has, then the login code is run, otherwise the form is displayed 
    if(!empty($_POST)) 
    { 
        // This query retrieves the user's information from the database using 
        // their email. 
        $query = " 
            SELECT 
                email 
            FROM users 
            WHERE 
                email = :email 
        "; 

        // The parameter values 
        $query_params = array( 
            ':email' => $emailaddress
        );   
        try 
        { 
            // Execute the query against the database 
            $stmt = $db->prepare($query); 
            $result = $stmt->execute($query_params); 
        } 
        catch(PDOException $ex) 
        {    
            die("Failed to run query"); 
        } 
        // This variable tells us whether the user has successfully logged in or not. 
        // We initialize it to false, assuming they have not. 
        // If we determine that they have entered the right details, then we switch it to true. 
        $login_ok = false; 

        // Retrieve the user data from the database.  If $row is false, then the email
        // they entered is not registered. 

         $row = $stmt->fetch(); 
         if($row) { 
         $login_ok = true; 
         }  
        // If the user logged in successfully, then we send them to the private members-only page 
        // Otherwise, we display a login failed message and show the login form again 
        if($login_ok) 
        { 

            // This stores the user's data into the session at the index 'user'. 
            // We will check this index on the private members-only page to determine whether 
            // or not the user is logged in.  We can also use it to retrieve 
            // the user's details. 
            $_SESSION['user'] = $row; 

            // Redirect the user to the private members-only page. 
           echo 'redirect';
        } 
        else 
        { 
            // Tell the user they failed 
            echo 'That email address is not registered';            
        } 
    } 

?>

I've rewritten the code for you as it likes like you had quite a few problems.

 $(document).ready(function() {

    $("#loginform").submit(function(e){
        e.preventDefault();

        jQuery.ajax({
                type: "POST",
                url: "login/login.php",
                dataType:"text",
                data: { email: $('#email').val(), loginsubmit: 'yes' },
                success:function(response){

                    if(response == "redirect"){
                        window.location.replace("http://www.gathercat.com/login/private.php"); 
                    }
                    else{
                        $("#formResponse").html(response).fadeIn('100');
                        $('#email').val('');   
                    }
                }
            })
    });
});

This is untested but please let me know if you have any questions about how it works.

if ( formResponse === "redirect" ) ...

what is formResponse variable?

it should be data

if ( data == "redirect" ) ...

UPDATE: may be this will help

$(document).ready(function () {
    $("#loginform").submit(function (e) {
        e.preventDefault();
        $.post('login/login.php', {
            email: $('#email').val(),
            loginsubmit: 'yes'
        }, function (data) {
            if (data === "redirect") {
                window.location = "http://www.gathercat.com/login/private.php";
            } else {
                $("#formResponse").html(data).fadeIn('100');
                $('#email').val('');
            }}, 'text');

            // this does not matter
            return false;
        }

        // add line below
        return false;
    });
});

Ok, I solved it!

I changed my ajax to:

<script>
 $(document).ready(function() {

    $("#loginform").submit(function(e){
        e.preventDefault();

        $.ajax({
                type: "POST",
                url: "login/login.php",
                dataType:"text",
                data: {email: $('#emailaddy').val(), loginsubmit: 'yes'},
                success:function(result){

                    if(result === "redirect"){
                     //  window.location.replace("login/private.php"); 
                      window.location.replace("http://www.gathercat.com/login/private.php");
                        //alert(result);
                    }
                    else{

                        $("#formResponse").html(result).fadeIn('100');
                        $('#emailaddy').val('');   
                    }
                                     }
            })
    });
});
</script>

and removed some commented-out HTML within the bottom of my php file which was disrupting the "result" variable's content. Everything runs perfectly now. I added this answer so people could see the full code easily, but I'm giving massive credit to paddyfields for their help, thank you again. You too Lee, appreciate the support. Take care