How to return PHP response to HTML page using AJAX

Shrey

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.

Shrey

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">

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How can show AJAX response as HTML page?

From Dev

How can show AJAX response as HTML page?

From Dev

Ajax Call using Jquery in HTML and take a response to other Html Page

From Dev

How to return output on the same page ajax php

From Dev

Search function on PHP/HTML page using AJAX

From Dev

HTML from servlet response using ajax is not being executed in JSP page

From Dev

Sending data to php page using ajax and get response and show in fields

From Dev

How to pass user input value from a PHP page to HTML page using AJAX

From Dev

How to pass user input value from a PHP page to HTML page using AJAX

From Dev

how to return an array from php to ajax response in javascript

From Dev

How to return HTML from controller using ajax?

From Dev

How to return html of a page using robobrowser

From Dev

i need to return an entire html page using an ajax call

From Dev

How to return an object in response using ajax in liferay portlet?

From Dev

how to get JSON response from servlet to jsp page by using ajax

From Dev

Ajax return full html page

From Dev

In Ajax How to pass country name in html page to php page?

From Dev

How to return specific table from page using Ajax reload

From Dev

How to return specific table from page using Ajax reload

From Dev

how to get response from node server using ajax method in html

From Dev

$ajax success response print HTML page

From Dev

How to get data from one php page using ajax and pass it to another php page using ajax

From Dev

PHP and Ajax does not always return a response

From Dev

How to get response from PHP file as an array using Ajax?

From Dev

getting response from php page to ajax?

From Dev

getting response from php page to ajax?

From Dev

Jquery Ajax & PHP - Return a Variable and PHP Page

From Dev

Ajax request for PHP to return HTML

From Dev

How to response with HTML page SparkJava

Related Related

  1. 1

    How can show AJAX response as HTML page?

  2. 2

    How can show AJAX response as HTML page?

  3. 3

    Ajax Call using Jquery in HTML and take a response to other Html Page

  4. 4

    How to return output on the same page ajax php

  5. 5

    Search function on PHP/HTML page using AJAX

  6. 6

    HTML from servlet response using ajax is not being executed in JSP page

  7. 7

    Sending data to php page using ajax and get response and show in fields

  8. 8

    How to pass user input value from a PHP page to HTML page using AJAX

  9. 9

    How to pass user input value from a PHP page to HTML page using AJAX

  10. 10

    how to return an array from php to ajax response in javascript

  11. 11

    How to return HTML from controller using ajax?

  12. 12

    How to return html of a page using robobrowser

  13. 13

    i need to return an entire html page using an ajax call

  14. 14

    How to return an object in response using ajax in liferay portlet?

  15. 15

    how to get JSON response from servlet to jsp page by using ajax

  16. 16

    Ajax return full html page

  17. 17

    In Ajax How to pass country name in html page to php page?

  18. 18

    How to return specific table from page using Ajax reload

  19. 19

    How to return specific table from page using Ajax reload

  20. 20

    how to get response from node server using ajax method in html

  21. 21

    $ajax success response print HTML page

  22. 22

    How to get data from one php page using ajax and pass it to another php page using ajax

  23. 23

    PHP and Ajax does not always return a response

  24. 24

    How to get response from PHP file as an array using Ajax?

  25. 25

    getting response from php page to ajax?

  26. 26

    getting response from php page to ajax?

  27. 27

    Jquery Ajax & PHP - Return a Variable and PHP Page

  28. 28

    Ajax request for PHP to return HTML

  29. 29

    How to response with HTML page SparkJava

HotTag

Archive