user3573301 user3573301 - 2 months ago 10
PHP Question

Ajax/Jquery issue pushing data to backend

Firstly I'm not sure if missing anything in my code other than the problems in my functions, but i digress. I'm new to jquery so I'm having difficulty setting up a registration page. In the form I'm trying to check for valid entries as well as checking the queries in the back-end using php. I set up 2 files one is an html file and the other is a php file. Using ajax the function was supposed to call the php file, but I cant seem to get it working and I'm wondering if I should just put all the code in the same file. Furthermore I'm unsure if the functions are even working at all because its not returning any status. I will post the code for the two files below. Any hints or tips would be greatly appreciated.

The HTML file without css

<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Register</title>

<link rel="stylesheet" href="assets/css/reset.css">
<link rel="stylesheet" href="assets/css/style.css">

</head>

<body>
<script src="assets/js/jquery.min.js"> </script>
<script src="assets/js/main.js"> </script>


<div class="pen-title">
<h1>Registration Form</h1></div>

<script>
function emptyElement(x){
_(x).innerHTML = "";
}
function signup(){
var u = _("username").value;
var e = _("email").value;
var p1 = _("pass").value;
var p2 = _("pass2").value;
var status = _("status");
if(u == "" || e == "" || p1 == "" || p2 == ""){
status.innerHTML = "Fill out all of the form data";
} else if(p1 != p2){
status.innerHTML = "Your password fields do not match";
} else
{
_("submit").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "registration.php");
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "signup_success"){
status.innerHTML = ajax.responseText;
_("submit").style.display = "block";
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
}
}
}
ajax.send("u="+u+"&e="+e+"&p="+p1);
}
}
</script>



<!-- Form Module-->
<div class="module form-module">
<div class="form">
</div>
<div class="form">
<h2>Create an account</h2>
<form method="post" name="signupform" id="signupform" onsubmit="return false;">
<input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
<input type="password" id="pass" onfocus="emptyElement('status')" placeholder="Password" maxlength="10"/>
<input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
<input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
<!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
<button type="submit" onclick="signup()" name="submit">Register</button>
</form>
</div>
</div>


</body>
</html>


The PHP file

<?php
// Connects to your Database

$host="myhost"; // Host name
$username="myuser"; // Mysql username
$password="mypass"; // Mysql password
$db_name="mydbname"; // Database name

$con = mysqli_connect("$host", "$username", "$password", "$db_name") or die(mysql_error());

// Ajax calls this REGISTRATION code to execute
if(isset($_POST["u"])){
// GATHER THE POSTED DATA INTO LOCAL VARIABLES
$u = preg_replace('#[^a-z0-9]#i', '', $_POST['u']);
$e = mysqli_real_escape_string($con, $_POST['e']);
$p = $_POST['p'];
// GET USER IP ADDRESS
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));
// DUPLICATE DATA CHECKS FOR USERNAME AND EMAIL
$sql = "SELECT id FROM users WHERE username='$u' LIMIT 1";
$query = mysqli_query($con, $sql);
$u_check = mysqli_num_rows($query);
// -------------------------------------------
$sql = "SELECT id FROM users WHERE email='$e' LIMIT 1";
$query = mysqli_query($con, $sql);
$e_check = mysqli_num_rows($query);
// FORM DATA ERROR HANDLING
if($u == "" || $e == "" || $p == ""){
echo "The form submission is missing values.";
exit();
} else if ($u_check > 0){
echo "The username you entered is alreay taken";
exit();
} else if ($e_check > 0){
echo "That email address is already in use in the system";
exit();
} else if (strlen($u) < 3 || strlen($u) > 16) {
echo "Username must be between 3 and 16 characters";
exit();
} else if (is_numeric($u[0])) {
echo 'Username cannot begin with a number';
exit();
} else {
// END FORM DATA ERROR HANDLING
// Begin Insertion of data into the database
// Hash the password and apply your own mysterious unique salt
//$cryptpass = crypt($p);
//include_once ("php_includes/randStrGen.php");
//$p_hash = randStrGen(20)."$cryptpass".randStrGen(20);
// Add user info into the database table for the main site table
$sql = "INSERT INTO users (username, email, password, ip, signup, lastlogin, notescheck)
VALUES('$u','$e','$p' ,'$ip',now(),now(),now())";
$query = mysqli_query($con, $sql);
$uid = mysqli_insert_id($con);
// Establish their row in the useroptions table
$sql = "INSERT INTO useroptions (id, username, background) VALUES ('$uid','$u','original')";
$query = mysqli_query($db_conx, $sql);
// Create directory(folder) to hold each user's files(pics, MP3s, etc.)
//if (!file_exists("user/$u")) {
// mkdir("user/$u", 0755);
//}
}
}
?>

Answer

Your javascript code has many errors. Like you used _ instead of $ and your element Ids is wrong. They are not include #. So I have organized your code with your logic. Bu it is not a real question or it is not a true way to learn. HTML

<!DOCTYPE html>
<html >
  <head>
    <meta charset="UTF-8">
    <title>Register</title>

    <link rel="stylesheet" href="assets/css/reset.css">
    <link rel="stylesheet" href="assets/css/style.css">    

  </head>

  <body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<!--script src="assets/js/main.js"> </script-->


<div class="pen-title">
  <h1>Registration Form</h1></div>

  <script>
  function emptyElement(x){
    $('#' + x).text("");
}
  function signup(){
    var un = $("#username").val();
    var em = $("#email").val();
    var p1 = $("#pass").val();
    var p2 = $("#pass2").val();
    if(un == "" || em == "" || p1 == "" || p2 == "")
    {
        $('#status').text("Fill out all of the form data");
    } 
    else if(p1 != p2)
    {
        $('#status').text("Your password fields do not match");
    } 
    else 
    {

        $.ajax({
            type: "POST",
            url: "registration.php",
            dataType: "json",
            data : { u: un, p:p1, e:em },
            cache: !1,
            beforeSend: function(){
                $("#submit").hide();
                $('#status').text('please wait ...');
            },
            complete: function(){
                $("#submit").show();
            },
            success: function(answer){
                if(answer.result == "successful")
                {
                    $("#status").html(answer.text);
                }
                else
                {
                    $("#status").html(answer.result);
                }
            },
            error: function(answer){
                $("#status").text(answer);
            }
        });
    }

        /*
        var ajax = ajaxObj("POST", "registration.php");
        ajax.onreadystatechange = function() {
            if(ajaxReturn(ajax) == true) {
                if(ajax.responseText != "signup_success"){
                    status.innerHTML = ajax.responseText;
                    $("submit").style.display = "block";
                } else {
                    window.scrollTo(0,0);
                    $("signupform").innerHTML = "OK "+u+", check your email inbox and junk mail box at <u>"+e+"</u> in a moment to complete the sign up process by activating your account. You will not be able to do anything on the site until you successfully activate your account.";
                }
            }
        }
        ajax.send("u="+u+"&e="+e+"&p="+p1);
        */
    }
</script>



<!-- Form Module-->
<div class="module form-module">
    <div class="form">
         </div>
  <div class="form">
    <h2>Create an account</h2>
    <form method="post" name="signupform" id="signupform" onsubmit="return false;">
      <input type="text" id="username" onfocus="emptyElement('status')" placeholder="Username" maxlength="50"/>
      <input type="password" id="pass" onfocus="emptyElement('status')"  placeholder="Password" maxlength="10"/>
      <input type="password" id="pass2" onfocus="emptyElement('status')" placeholder="Confirm Password" maxlength="10"/>
      <input type="email" id="email" onfocus="emptyElement('status')" placeholder="Email Address" maxlength="50"/>
      <!-- <input type="tel" name="telephone" placeholder="Phone Number" maxlength="10"/> -->
      <button type="submit" onclick="signup()" name="submit">Register</button>
      <div id="status"></div>
    </form>
  </div>
</div>


  </body>
</html>

registration.php

<?php
    $answer = new stdClass;
    if(isset($_POST))
    {
        $answer->result = "successful";
        $answer->text = "";
        foreach($_POST as $key => $value)
        {
            $answer->text .= $key . ": " . $value . "<br />";
        }
    }
    else
    {
        $answer->result = "Error";
        $answer->text = "Error Message";
    }
    echo json_encode($answer);
?>

This registration.php is an example for you. You can rewrite with your logic. You should use $answer object for response.
$answer->result is status of repsonse $answer->text is response I hope it will help you.