简体   繁体   English

使用AJAX提交登录表单并获得回复

[英]Submit Login Form Using AJAX and get response

I am trying to build a front end HTML page that takes in a username and password and then uses a javascript function to show response depending on the answer received from the server. 我正在尝试构建一个使用用户名和密码的前端HTML页面,然后使用javascript函数显示响应,具体取决于从服务器收到的答案。 I am a super noob when it comes to web development so can anyone help me correct my code ? 在Web开发方面,我是一个超级菜鸟,所以有人可以帮助我更正我的代码吗? Thank you 谢谢

This is my index.php 这是我的index.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <type="text/javascript"></script>
        <script type="text/javascript" src="jquery.js"></script>
        <link rel="stylesheet" href="styles.css" type="text/css" />
        <title>Login Form</title>
        <script type="text/javascript">
            $(document).ready(function(){
                $("#login").click(function(){
                    username=$("#user_name").val();
                    password=$("#password").val();

                    $.ajax({
                        type    : "POST",
                        url     : "login.php",
                        data    : "username="+username+"&password="+password,
                        success : function(html){
                            if(html=='true'){
                                $("#add_err").html("right username And password");
                                //$("#login_form").fadeOut("normal");
                                //$("#shadow").fadeOut();
                                //$("#profile").html("<a href='logout.php' class='red' id='logout'>Logout</a>");    
                            }else{
                                $("#add_err").html("Wrong username And password");
                            }
                        },
                        beforeSend:function(){
                            $("#add_err").html("Loading...")
                        }
                    });
                    return false;
                });
            });
        </script>
    </head>
    <body>
    <?php session_start(); ?>
        <div id="profile">
            <?php if(isset($_SESSION['user_name'])){ ?>

            <?php } ?>
        </div>
    </body>

    <?php if(empty($_SESSION['user_name'])){ ?>
    <div class="container" id="login_form">
        <section id="content">
            <form action="login.php">
                <h1>Login Form</h1>
                <div>
                    <input type="text" placeholder="Username" required="" id="user_name"  name="user_name"/>
                </div>
                <div>
                    <input type="password" placeholder="Password" required="" id="password"  name="password"/>
                </div>
                <div class="err" id="add_err"></div>
                <div>
                    <input type="submit" value="Log in" id="login"  />
                </div>
            </form>
            <div class="button"> </div> 
        </section>
    </div>
    <?php } ?>

</html>

And this is my login.php code which uses curl to forward username/pass to appropriate url 这是我的login.php代码,它使用curl将用户名/密码转发给适当的URL

<?php

session_start();
$url =  http://    //url that recieves username/password and responds if credentials are correct after contacting database
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;

?>  

javascript JavaScript的

$("#login").click(function(){
  $.ajax({
    type: 'POST', 
    url: 'login.php', 
    dataType: 'json',
    data: $('#Form').serialize(),
    success: function (x) {                
      $("#add_err").html(x.response);
    },
    beforeSend:function(){
      $("#add_err").html("Loading...")
    }
  });
  return false;
});

html form html表格

   <form id="Form" action="login.php">
        <h1>Login Form</h1>
        <div>
            <input type="text" placeholder="Username" required="" id="user_name"  name="user_name"/>
        </div>
        <div>
            <input type="password" placeholder="Password" required="" id="password"  name="password"/>
        </div>
            <div class="err" id="add_err"></div>
        <div>
                <input type="submit" value="Log in" id="login"  />
        </div>
    </form>

php PHP

<?php
session_start();
header('Content-Type: application/json');
$url =  http://    //url that recieves username/password and responds if     credentials are correct after contacting database
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($_POST));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
$output=array(); 
$output['response']=$result;    
echo json_encode($output);
?>  

Alright, first things first: you can use action="form.php" OR the click handler $("#login").click(function(){}); 好吧,首先要做的是:您可以使用action="form.php"或单击处理程序$("#login").click(function(){}); . Using both is redundant and will make your javascript form checker void. 同时使用两者是多余的,这会使您的JavaScript表单检查器无效。

So go ahead and remove action="login.php" . 因此,继续删除action="login.php"

Next step is making sure your login.php script is receiving everything correctly. 下一步是确保您的login.php脚本正确接收了所有内容。 For debug purposes, add 出于调试目的,添加

var_dump($_POST);
exit();

To the top of login.php , then add login.php的顶部,然后添加

console.debug(html); 

To the top of your ajax success function. 在ajax success函数的顶部。 That'll show you in the console what the PHP script is seeing for $_POST variables. 这将在控制台中显示$_POST变量的PHP脚本。

Hopefully that helps you get started on diagnosing whatever issue is going on. 希望这可以帮助您开始诊断正在发生的任何问题。

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

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