doumo1807831
2016-02-02 20:29
浏览 334

如何使用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">
    
    打赏 评论
  • dreamact3026 2016-02-02 22:49

    Try using a more flexible jQuery ajax. I use this version if ajax because I can change it to get and post very easily. I have tested this method and it works with your form:

    <script>
    function clearInput() {
        $("#register-form :input").each( function() {
           $(this).val('');
        });
    }
    $(document).ready(function() {
        $("#register-form").submit(function(e) {
            //console.log($(this).attr("action"));
            $.ajax({
                url: $(this).attr("action"),
                type: 'post',
                data: $(this).serialize(),
                success: function(response)
                    {
                        // console.log(response);
                        $("#signin-test").html(response);
                        clearInput();
                    },
                error: function(response)
                    {
                        console.log(response);
                    }
            });
    
            e.preventDefault();
        });
    });
    </script>
    
    打赏 评论
  • dtnmnw3697 2016-02-04 00:59

    This may be because you are handling your form based on the behavior of a button. You should be listening for the onSubmit event of the form and preventing that from firing.

    $("#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();
    });
    
    打赏 评论

相关推荐 更多相似问题