简体   繁体   English

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

[英]How to redirect user on successful ajax call? Otherwise display error message in form

Updated: Thanks for reading - My login form calls on login.php to check whether the user has entered a registered email address or not. 更新:感谢您的阅读-我的登录表单调用login.php来检查用户是否输入了注册的电子邮件地址。 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. 由于将表单操作设置为#,所以我当前的代码仅重定向到mydomain.com/#,因为我正在使用ajax提交表单。

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"? 如果php已回显“重定向”,则将用户重定向到private.php页面-否则,如果回显“未注册电子邮件” ,如何在表单内显示“未注册电子邮件”? My login form contains a div to display the error if necessary. 我的登录表单包含一个div,以在必要时显示错误。

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

<?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';            
        } 
    } 

?>

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

what is formResponse variable? 什么是formResponse变量?

it should be data 应该是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;
    });
});

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. 这未经测试,但是如果您对它的工作方式有任何疑问,请告诉我。

Ok, I solved it! 好的,我解决了!

I changed my ajax to: 我将ajax更改为:

<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. 并删除了我的php文件底部的一些注释掉的HTML,这破坏了“结果”变量的内容。 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 照顾自己

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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