如何使用AJAX将PHP响应返回到HTML页面

时间:2016-02-02 20:29:03

标签: php jquery html ajax

我正在尝试学习Web应用程序,这里我的客户端使用HTML和服务器是基于PHP的。 我从我的客户端注册,填写后点击提交按钮使用jQuery AJAX发送到PHP页面。 因此,在使用AJAX将表单数据发送或POST到PHP页面之后,会发生一些验证,如检查用户名和电子邮件,如果验证成功,它应该将JSON对象发送回我的HTML页面" SUCCESS" ,如果验证失败"错误"。

所以,问题是当我提交表单时,它会将我重定向到PHP页面,而不是在我的html上显示JSON响应。

自上周以来,我试图解决这个问题,我过滤了堆栈溢出,youtube和许多其他网站以寻求解决方案,但这并不顺利。

这是代码

PHP:

<?php include ( "./inc/connect.inc.php" ); 
header("Content-type: application/javascript");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, GET");

session_start();
if (isset($_SESSION['user_login'])) {
    $user = $_SESSION["user_login"];
}
else
{
    $user = "";
}
?>

<?php
$registration = @$_POST['signup-submit'];

$fname    = @$_POST['fname'];
$lname    = @$_POST['lname'];
$uname    = @$_POST['uname'];
$email    = @$_POST['email'];
$email_repeat = @$_POST['email_repeat'];
$password = @$_POST['password'];

$ucheck_array = array('Username Takne');
$echeck_array = array('Email already used');
$siginup_sucess_array = array('Sucess');

//Sign-Up form validation
if ($registration) {    
$usernamecheck = mysql_query("SELECT * FROM users WHERE username='$uname' ");
$usernamecount = mysql_num_rows($usernamecheck);
$emailcheck = mysql_query("SELECT * FROM users WHERE email='$email' ");
$emailcount = mysql_num_rows($emailcheck);
if ($usernamecount == 0 && $emailcount == 0) {
    $squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$dob','$location','$email','$password','$date','0','','','','','','no')" ); 
        echo json_encode($siginup_sucess_array);
}       
else {
    if ($usernamecount == 1) {
        echo json_encode($ucheck_array);
    }
    else if ($emailcount == 1) {
        echo json_encode($echeck_array);
    }
}
}

HTML表格:

<form id="register-form" class="animated fadeInRight" action="http://localhost/Exercises/AJAX/df.php" method="post" role="form" style="display: none;">
    <div class="form-group">
        <input type="text" name="fname" id="fname" placeholder="First Name" value="" autofocus>
    </div>
    <div class="form-group">
        <input type="text" name="lname" id="lname" tabindex="1" class="form-control" placeholder="Last Name" value="">
    </div>
    <div class="form-group">
        <input type="text" name="uname" id="uname" tabindex="1" class="form-control" placeholder="User Name" value="">
    </div>
    <div class="form-group">
        <input type="text" name="dob" id="dob" placeholder="D-O-B" value="">
    </div>
    <div class="form-group">
        <input type="text" name="location" id="location" tabindex="1" class="form-control" placeholder="Location" value="">
    </div>
    <div class="form-group">
        <input type="email" name="email" id="email" placeholder="Email" value="">
    </div>
    <div class="form-group">
        <input type="email" name="email_repeat" id="email_repeat" placeholder="Confirm Email" value="">
    </div>
    <div class="form-group">
        <input type="text" name="password" id="password" tabindex="1" class="form-control" placeholder="Password" value="">
    </div>
    <div class="form-group dob">
        <input type="text" name="date" id="date" placeholder="Date" value="">
    </div>
    <p class="index_p">By creating the account you accept all the <span style="color: #4CAF50; font-weight: bold; text-decoration: underline;">Terms & Conditions.</span></p>
    <div class="form-group">
        <div class="row">
            <div id="btn_signin" class="col-sm-6 col-sm-offset-3">
                <input type="submit" name="signup-submit" id="signup-submit"  value="SIGN UP">
            </div>
        </div>
    </div>
</form>
<div id="signup-test"></div> //PHP response to be displayed here

JS:

$("#signup-submit").click( function() {
    $.post( $("#register-form").attr("action"),
        $("#register-form :input").serializeArray(), 
            function(signup_data){
                $("#signup-test").html(signup_data);
            });
clearInput();
});

$("#register-form").submit( function() {
    return false;   
});

function clearInput() {
    $("#register-form :input").each( function() {
       $(this).val('');
    });
}

要明确我尝试了e.preventDefaultreturn false和许多其他脚本, 我的PHP和HTML不在同一个文件夹或目录中。 谢谢。

3 个答案:

答案 0 :(得分:0)

尝试使用更灵活的jQuery ajax。我使用这个版本,如果ajax因为我可以很容易地改变它来获取和发布。我已经测试了这种方法,它适用于您的表单:

    import java.io.*;


    File thisun = new File("C:\\Users\\CH\\Documents\\dictionary.txt");
    System.out.println(thisun.canRead());

答案 1 :(得分:0)

这可能是因为您根据按钮的行为处理表单。您应该正在侦听表单的onSubmit事件并阻止它被触发。

$("#register-form").submit( function( e ) {
    e.preventDefault(); 
    $.post( $("#register-form").attr("action"),
        $("#register-form :input").serializeArray(), 
            function(signup_data){
                $("#signup-test").html(signup_data);
            });
clearInput();
});

答案 2 :(得分:0)

我用以下脚本解决了它,希望它可以帮助某人。 我尝试的所有脚本的问题是,他们没有 XMLHttpRequest 权限来POST数据并从PHP获取数据(在我的情况下是服务器端)。

因此, XMLHttpRequest 是Ajax获取或发布数据“CROSS_DOMAIN”的必需品。

脚本:

function signup(){
var firstname    = document.getElementById("firstname").value;
var lastname     = document.getElementById("lastname").value;
var uname        = document.getElementById("uname").value;
var email        = document.getElementById("email").value;
var email_repeat = document.getElementById("email_repeat").value;
var password     = document.getElementById("password").value;

if (fname == "") {
    document.getElementById("fname").style.background = "rgba(244,67,54,0.45)";
    document.getElementById("fnamestatus").innerHTML = "<p style='width: 30px; color: rgba(255, 62, 48, 0.9); font-size: 14px; font-weight: bold; margin-top:5px; margin-left: -40px; margin-bottom: 0px;'>2-25</p>";    
}

else if (email != email_repeat){
    document.getElementById("email").style.background = "rgba(244,67,54,0.45)";
    document.getElementById("email_repeat").style.background = "rgba(244,67,54,0.45)";
    alert("Your email fields do not match");
}

else {
    var signup_ajax = new XMLHttpRequest();
    signup_ajax.open("POST", "URL which you want to post data", true);
    signup_ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    signup_ajax.onreadystatechange = function () {
        if (signup_ajax.readyState == 4 && signup_ajax.status == 200) {
            if (signup_ajax.responseText = "Success"){
                alert("Account created");
            } 
            else if (signup_ajax.responseText = "Try again.") {
                window.scrollTo(0,0);
                alert("Try again.");
            }
        }
    }
    signup_ajax.send("fname=" +fname+ "&lname=" +lname+ "&uname=" +uname+ "&email=" +email+ "&email_repeat=" +email_repeat+ "&password=" +password );
    } 
 }

PHP(我只是发布基本的php,您可以随时添加可能的验证):

if(isset($_POST["uname"])) {

$fname    = @$_POST['firstname'];
$lname    = @$_POST['lastname'];
$uname    = @$_POST['uname'];
$email    = @$_POST['email'];
$email_repeat = @$_POST['email_repeat'];
$password = @$_POST['password'];

//Sign-Up form validation
if($_POST) {
    $squery = mysql_query("INSERT INTO users VALUES ('','$uname','$fname','$lname','$email','$password')" ); 
        echo 'Sucess';
}       
else 
    echo 'Try again.';
}

仅将我对 HTML 表单所做的更改为:

<input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">