doumo1807831 2016-02-02 20:29
浏览 369
已采纳

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

I am trying to learn web applications, here I have my client side using HTML and server is PHP based. I have signup from on my client side, which when filled and click submit button is sent to PHP page using jQuery AJAX. So, after the form data is sent or POST to PHP page using AJAX, a couple of validations happen like checking username and email, if the validations succeed it should send back a JSON object to my HTML page "SUCCESS", if validation fails "Error".

So, the problem is when I submit the form it is redirecting me to the PHP page instead of displaying the JSON response back on my html.

I was trying to solve this since last week and I filtered stack overflow, youtube and many other sites for a solution, which didn't go well.

Here is the code

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:

<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('');
    });
}

To be clear I tried e.preventDefault, return false and many other scripts, and my PHP and HTML are not in the same folder or directory. Thanks.

  • 写回答

3条回答 默认 最新

  • dtkago3208 2016-02-05 03:04
    关注

    I solved it with the following script, hope it would help someone. The problem with all the scripts which I tried is, they don't have XMLHttpRequest permission to POST data and get the data back from PHP(server side in my case).

    So, XMLHttpRequest is a must for Ajax to Get or Post data "CROSS_DOMAIN".

    Script :

    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(I'm just posting the basic php, you can always add as may validations as you need) :

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

    Only change what I did to my HTML Form is :

    <input type="button" name="signup-submit" id="signup-submit" class="form-control btn btn-signup" onclick="signup()" tabindex="4" value="SIGN UP">
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码