简体   繁体   English

PHP代码返回其脚本,在JQuery Ajax中不起作用

[英]PHP Code Returns Its Script and Doesn't Work in JQuery Ajax

I would like to do a web site using Aptana IDE and xampp, and it has a few pages. 我想使用Aptana IDE和xampp做一个网站,它有几页。 Index page is where all users which does not log in the system and home is where all users which does log in the system must visit. 索引页面是指未登录系统和主页的所有用户必须访问系统的所有用户所在的位置。 I am very new to develop web site. 我是开发网站的新手。

I decided to use Ajax for log in sign up pages. 我决定使用Ajax登录注册页面。 It was actually works properly. 它实际上是正常的。 But now I do not know why it does not. 但现在我不知道为什么不这样做。

In my login.html page 在我的login.html页面中

<form id="login-form" class="text-left" method="post">
                <div class="main-login-form">
                    <div class="login-group">
                        <div class="form-group">
                            <label for="lg_username" class="sr-only">Username</label>
                            <input type="text" class="form-control" id="lg_username" name="username" placeholder="username"
                                   data-container="body" data-toggle="popover" data-placement="left" data-content=""
                                   value="">
                        </div>
                        <div class="form-group">
                            <label for="lg_password" class="sr-only">Password</label>
                            <input type="password" class="form-control" id="lg_password" name="password" placeholder="password" 
                                   data-container="body" data-toggle="popover" data-placement="left" data-content="">
                        </div>
                        <div class="form-group login-group-checkbox">
                            <input type="checkbox" id="lg_remember" name="lg_remember">
                            <label for="lg_remember">remember</label>
                        </div>
                    </div>
                    <button type="submit" class="login-button">Submit</button>
                </div>
            </form>

and form validate with JQuery validation 并使用JQuery验证进行表单验证

$(document).ready(function () {
        $('#login-form').validate({
    rules: { //rules goes here},
    messages: { //messages goes here},
    submitHandler: submitForm
});

It works correctly. 它工作正常。 All my rules are implemented. 我的所有规则都已实施。

submit function: 提交功能:

function submitForm(){
            var username = $('#lg_username').val();
            var password = $('#lg_password').val();
            var checkbox = $('#lg_remember').is(":checked");

            var strAjax = "username=" + username + "&password=" + password + "&checkbox=" + checkbox;
            alert(strAjax);
            $.ajax({
                type: 'POST',
                url: 'loginAjax.php',
                data: strAjax,
                cache: false,
                success: function(data) {
                    alert(data);
                    if(data == "1") {
                        window.location.href = "home.php";
                    }
                    else {
                        //Error messages
                    }
                }
            });
            return false;
            }

loginAjax.php file: loginAjax.php文件:

<?php
require_once 'dbcon.php';
session_start();

$username = mysql_real_escape_string($_POST["username"]);
$password = mysql_real_escape_string($_POST["password"]);

$sql = "SELECT * FROM tbl_user WHERE userName = '$username' AND password = '$password'";

$result = mysql_query($sql);
$count = mysql_num_rows($result);
$row = mysql_fetch_array($result);

if($count == 1){
    if($_POST['checkbox'] == TRUE) {
        if(!isset($_COOKIE['name'])) {
            setcookie( 'name', $row['userName'], time() + (86400 * 30) );
        }
    }
    $_SESSION['user_session'] = $row['userName'];
    echo TRUE;
}
else {
    echo FALSE;
}
?>

dbcon.php file connect to mysql database. dbcon.php文件连接到mysql数据库。 I try to control is it enter the ajax method or what is returning from php file with alert. 我试着控制它是进入ajax方法还是从带有警报的php文件返回的内容。 strAjax seems correct but alert(data) show my php code like this; strAjax似乎是正确的但警报(数据)显示我的PHP代码是这样的;

php returns this php返回此信息

I change login file as php file instead html. 我将登录文件更改为php文件而不是html。 But the problem is not about it. 但问题不在于此。 All my ajax codes get data from php something like that. 我所有的ajax代码都从php中获取数据。 In my computer php files run normally. 在我的电脑php文件正常运行。 If you need more information I can edit my post. 如果您需要更多信息,我可以编辑我的帖子。 Why this ajax conk? 为什么这个ajax conk?

var formData = {
    'username'              : $('input[name=username]').val(),
    'password'             : $('input[name=password]').val(),
    'lg_remember'    : $('input[name=lg_remember]').val()
};

// process the form
$.ajax({
    type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
    url         : 'process.php', // the url where we want to POST
    data        : formData, // our data object
    dataType    : 'json', // what type of data do we expect back from the server
                encode          : true
})

Try this one instead 试试这个

Problem is your ajax code. 问题是你的ajax代码。 You are using POST method and passing parameter as query string. 您正在使用POST方法并将参数作为查询字符串传递。 You just need to use serialize() for passing data. 您只需要使用serialize()来传递数据。

Just change your ajax code with this : 只需更改您的ajax代码:

$.ajax({
                type: 'POST',
                url: 'loginAjax.php',
                data: $('#login-form').serialize(),
                cache: false,
                success: function(data) {
                    alert(data);
                    if(data == "1") {
                        window.location.href = "home.php";
                    }
                    else {
                        //Error messages
                    }
                }
            });

And just remove strAjax variable, it's not required. 只需删除strAjax变量,就不需要了。

Side note : Please dont use mysql_* . 旁注:请不要使用mysql_* It is deprecated and removed from PHP 7. Use mysqli_* or PDO 它已被弃用并从PHP 7中删除。使用mysqli_*PDO

尝试在ajax函数上使用data: $("#login-form").serialize()

Add this to your loginAjax.php on the second line 将其添加到第二行的loginAjax.php中

 header('Content-Type: application/json');

note: your url should be: 注意:您的网址应为:

url         : 'loginAjax.php',

I have figured out. 我已经想通了。 Previously I try to connect with http://127.0.0.1:8020/ . 以前我尝试连接http://127.0.0.1:8020/ When I changed this as localhost all problem has gone. 当我将其更改为localhost时,所有问题都已消失。 Thank you all I appreciate all your efford. 谢谢大家,我感谢你所有的efford。

<html>
<head>
    <title></title>
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
    $('#login-form').on("submit", function(){
       $.ajax({
            type: 'POST',
            url: 'loginAjax.php',
            data: $("#login-form").serialize(),
            success: function(data) {
                alert(data);
                // if(data == "1") {
                //     window.location.href = "home.php";
                // }
                // else {
                //     //Error messages
                // }
            }
        });
       return false;
    });
});
</script>
<form id="login-form" class="text-left" method="post">
                <div class="main-login-form">
                    <div class="login-group">
                        <div class="form-group">
                            <label for="lg_username" class="sr-only">Username</label>
                            <input type="text" class="form-control" id="lg_username" name="username" placeholder="username"
                                   data-container="body" data-toggle="popover" data-placement="left" data-content=""
                                   value="">
                        </div>
                        <div class="form-group">
                            <label for="lg_password" class="sr-only">Password</label>
                            <input type="password" class="form-control" id="lg_password" name="password" placeholder="password"
                                   data-container="body" data-toggle="popover" data-placement="left" data-content="">
                        </div>
                        <div class="form-group login-group-checkbox">
                            <input type="checkbox" id="lg_remember" name="lg_remember">
                            <label for="lg_remember">remember</label>
                        </div>
                    </div>
                    <button type="submit" class="login-button">Submit</button>
                </div>
            </form>
</body>
</html>

try the whole page i just print_r() the result in php since you are using $() of jQuery i presume that you include the jQuery lib already, cheers bro. 尝试整个页面我只是print_r()结果在PHP,因为你使用$()的jQuery我假设你已经包含jQuery lib,欢呼兄弟。 try to use the code in a sample page. 尝试使用示例页面中的代码。

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

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