1

I am creating a PHP registration form using AJAX, the below code that I have pasted isn't working properly. I am literally new to this AJAX concept When I click the register button it won't respond and do anything, and even in the database the values are not getting stored. I have searched a lot for this AJAX concept. But I don't seem to get the result what I want. Please, can any one help me. Where am I actually doing the wrong thing? Thanks in advance!

index.php

                    <!DOCTYPE HTML>  
                    <html>
                    <head>
                        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
                        <script src="script.js"></script>
                    <style>
                    .error {
                        color:red;
                    }

                    .button {
                        background-color: #4CAF50;
                        border: none;
                        color: white;
                        padding: 10px 25px;
                        text-align: center;
                        text-decoration: none;
                        display: inline-block;
                        font-size: 16px;
                        margin: 4px 2px;
                        cursor: pointer;
                    }
                    .div1 {

                        margin-top: -19px;
                        margin-bottom: -25px;
                        margin-left: -19px; 
                    }

                    .copy {
                        border-radius: 4px;
                        padding: 6px 20px;
                       border-style: ridge;
                    }

                    .copy1{
                         border-radius: 4px;
                         padding: 6px 28px;
                         border-style: ridge;
                    }

                    .copy2{
                         border-radius: 4px;
                         padding: 4px 2px;

                    }
                    </style>
                    </head>
                    <body style="background-color: #f2f2f2;">  





                <?php
                // define variables and set to empty values
                include_once 'connect.php';

                $nameErr = $emailErr = $usernameErr = $passwordErr = $ageErr = "" ;
                $name = $email = $username = $password =  $age =  "";

                 if (isset($_POST['submit'])) {
                  if (empty($_POST["name"])) {
                    $nameErr = "Name is required";
                  } else {
                    $name = test_input($_POST["name"]);
                    // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
                      $nameErr = "Only letters"; 
                    }
                  }

                   if (empty($_POST["email"])) {
                    $emailErr = "Email is required";
                  } else {
                    $email = test_input($_POST["email"]);
                    // check if e-mail address is well-formed
                    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                      $emailErr = "Invalid email format"; 
                    }
                  }

                  if (empty($_POST["username"])) {
                    $usernameErr = "Username is required";
                  } else {
                    $username = test_input($_POST["username"]);
                     // check if name only contains letters and whitespace
                    if (!preg_match("/^[a-zA-Z ]*$/",$username)) {
                      $usernameErr = "Only letters"; 
                    }
                  }

                  if (empty($_POST["password"])) {
                    $passwordErr = "Password is required";
                  } else {
                    $password = test_input($_POST["password"]);
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    // check weather password is alphanumeric
                  if(!preg_match('/^(?=.*\d)(?=.*[A-Za-z])[0-9A-Za-z!@#$%]{6,}$/', $password))
                  {
                    $passwordErr = "Password must be alphanumeric and atleast 6 characters long!";
                  }
                  }



                    if (empty($_POST["age"])) {
                        $ageErr = "Age is required";
                    } 
                    elseif($_POST["age"]< 17 ) {
                        $ageErr = "Age should be above 18 years";
                    }
                    else {
                            $age = $_POST["age"];
                            }





                if($nameErr == "" && $emailErr == "" && $usernameErr == "" && $passwordErr == "" &&  $ageErr == "")
                  { 
                $check="SELECT * FROM users WHERE username = '$_POST[username]'";
                $rs = mysqli_query($mysqli,$check);
                $da = mysqli_fetch_array($rs, MYSQLI_NUM);
                if($da[0] > 0) {
                    echo "Username Already in Exists<br/>";
                }

                else
                {
                    $sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
                             VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";

                        if (mysqli_query($mysqli, $sql)) {
                        echo "Registered successfully";
                        } else {
                        echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
                        } 
                        mysqli_close($mysqli);
                }
                  }
                }

                function test_input($data) {
                  $data = trim($data);
                  $data = stripslashes($data);
                  $data = htmlspecialchars($data);
                  return $data;
                }
                ?>

                <div style="padding-left: 250px" class="div1">

                    <h2 style="color:#009999">Registration Form :</h2>
                    <p><span class="error">All fields are required </span></p>
                    <form action="" method="post" enctype="multipart/form-data">

                            <span style="color:#0099ff">Name: </span>
                            <input type="text" name="name" class= "copy" style="margin-left: 52px"  value ="<?php 
                                     if (isset($name)) 
                                      echo $name; 
                                 ?>">
                            <span class="error"> <?php echo $nameErr;?></span>
                            <br><br>

                            <span style="color:#0099ff"> E-mail: </span>
                            <input type="text" name="email" class= "copy" style="margin-left: 48px"  value ="<?php 
                                     if (isset($email)) 
                                      echo $email; 
                                 ?>">
                            <span class="error"><?php echo $emailErr;?></span>
                            <br><br>

                            <span style="color:#0099ff"> Username: </span>
                            <input type="text" name="username"  class= "copy" style="margin-left:26px"  value ="<?php 
                                     if (isset($username)) 
                                      echo $username; 
                                 ?>">
                            <span class="error"> <?php echo $usernameErr;?></span>
                            <br><br>

                            <span style="color:#0099ff"> Password: </span>
                            <input type="password" name="password"  class= "copy" style="margin-left:30px">
                            <span class="error"> <?php echo $passwordErr;?></span>
                            <br><br>



                            <span style="color:#0099ff">  Age : </span>
                            <input type="number" name="age"  class= "copy" style="margin-left:62px"  value ="<?php 
                                     if (isset($age)) 
                                      echo $age; 
                                 ?>">
                            <span class="error"> <?php echo $ageErr;?></span>
                            <br><br>



                            <input type="button" class="submit" name="submit" value="submit">   


                        </form>
                </div>
                </body>


                </html> 

script.js

        $(document).ready(function(){
        $(".submit").click(function(){
        var name = $("name").val();
        var email = $("email").val();
        var username = $("username").val();
        var password = $("password").val();
        var age = $("age").val();
        // Returns successful data submission message when the entered information is stored in database.
        var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;
        var dataString = $("form").serialize();
        if(name==''|| email==''|| username==''|| password==''|| age=='')
        {

        // AJAX Code To Submit Form.
        $.ajax({
        type: "POST",
        url: "index.php",
        data: dataString,
        cache: false,
        success: function(result){
        alert(result);
        }
        });
        }
        return false;
        });
        });

connect.php

        <?php


       $databaseHost = 'localhost';
       $databaseName = 'ajax1';
       $databaseUsername = 'root';
       $databasePassword = '';

       $mysqli = mysqli_connect($databaseHost, $databaseUsername, $databasePassword, $databaseName);

       ?>
Evading Shadows
  • 399
  • 4
  • 20
  • https://stackoverflow.com/q/1960240/4229270 – Sinto Jun 07 '18 at 09:25
  • can you show the code for index.php? – Conor Thompson Jun 07 '18 at 09:28
  • Here, seem like element value in not getting from the form because you are use wrong syntax to get element value. $("name").val(); suppose you element attribut id is name then you can write $("#name").val(); then you can get value of it. before data passing to ajax you have to check that data is collected proper or not. try to log dat in console. – Vishal Maru Jun 07 '18 at 09:28
  • can u edit my code n let me know sir please – kumar patil Jun 07 '18 at 09:51

2 Answers2

0

Try this... I hope it will help you..

index.php

 <!DOCTYPE HTML>  
                    <html>
                    <head>
                        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
                        <script src="script.js"></script>
                    <style>
                    .error {
                        color:red;
                    }

                    .button {
                        background-color: #4CAF50;
                        border: none;
                        color: white;
                        padding: 10px 25px;
                        text-align: center;
                        text-decoration: none;
                        display: inline-block;
                        font-size: 16px;
                        margin: 4px 2px;
                        cursor: pointer;
                    }
                    .div1 {

                        margin-top: -19px;
                        margin-bottom: -25px;
                        margin-left: -19px; 
                    }

                    .copy {
                        border-radius: 4px;
                        padding: 6px 20px;
                       border-style: ridge;
                    }

                    .copy1{
                         border-radius: 4px;
                         padding: 6px 28px;
                         border-style: ridge;
                    }

                    .copy2{
                         border-radius: 4px;
                         padding: 4px 2px;

                    }
                    </style>
                    </head>
                    <body style="background-color: #f2f2f2;">  






                <div style="padding-left: 250px" class="div1">

                    <h2 style="color:#009999">Registration Form :</h2>
                    <p><span class="error">All fields are required </span></p>
                    <form action="" method="post" enctype="multipart/form-data">

                            <span style="color:#0099ff">Name: </span>
                            <input type="text" name="name" class= "name copy" style="margin-left: 52px"  value ="">
                            <span class="namee error"> </span>
                            <br><br>

                            <span style="color:#0099ff"> E-mail: </span>
                            <input type="text" name="email" class= "email copy" style="margin-left: 48px"  value ="">
                            <span class="emaile error"></span>
                            <br><br>

                            <span style="color:#0099ff"> Username: </span>
                            <input type="text" name="username"  class= "username copy" style="margin-left:26px"  value ="">
                            <span class="usernamee error"></span>
                            <br><br>

                            <span style="color:#0099ff"> Password: </span>
                            <input type="password" name="password"  class= "password copy" style="margin-left:30px">
                            <span class="passworde error"> </span>
                            <br><br>



                            <span style="color:#0099ff">  Age : </span>
                            <input type="number" name="age"  class= "age copy" style="margin-left:62px"  value ="">
                            <span class="agee error"> </span>
                            <br><br>



                            <input type="button" class="submit" name="submit" value="submit">   


                        </form>
                </div>
                </body>
<script>
    $(document).ready(function(){
        $(".submit").click(function(){

        var name = $(".name").val();
        var email = $(".email").val();
        var username = $(".username").val();
        var password = $(".password").val();
        var age = $(".age").val();

    if(name==''){$('.namee').text('fill value'); return  false} 
    if(email==''){$('.emaile').text('fill value'); return  false}   
    if(username==''){$('.usernamee').text('fill value'); return  false} 
    if(password==''){$('.passworde').text('fill value'); return  false} 
    if(age==''){$('.agee').text('fill value'); return  false}   



        // Returns successful data submission message when the entered information is stored in database.
        var dataString = 'name='+ name + '&email='+ email + '&username='+ username + '&password='+ password + '&age='+ age;


        // AJAX Code To Submit Form.
        $.ajax({
        type: "POST",
        url: "gethint.php",
        data: dataString,
        cache: false,
        success: function(result){
        alert(result);
        }
        });

        });
        });
</script>


                </html> 

gethint.php

<?php



$mysqli  = mysqli_connect("localhost","root","","test");



$username =$_POST["username"];
$hashed_password=$_POST["password"];
$email=$_POST["email"];
$name=$_POST["name"];
$age=$_POST["age"];

                $check="SELECT * FROM users WHERE username = '$_POST[username]'";
                $rs = mysqli_query($mysqli,$check);
                $da = mysqli_fetch_array($rs, MYSQLI_NUM);
                if($da[0] > 0) {
                    echo "Username Already in Exists<br/>";
                }
                else
                {
                    $sql = "INSERT INTO users(`userid`,`username`, `password`, `email` , `name` , `age` )
                             VALUES ('','".$username."', '".$hashed_password."', '".$email."' , '".$name."' , '".$age."' )";

                        if (mysqli_query($mysqli, $sql)) {
                        echo "Registered successfully";
                        } else {
                        echo "Error: " . $sql . "<br>" . mysqli_error($mysqli);
                        } 
                        mysqli_close($mysqli);
                }


?>
Shazvan Hanif
  • 373
  • 2
  • 20
-1

The problem is when you run your index.php file for the first time , the php part gets executed.So make a new file for php part.

Get extra help From w3schools.com

https://www.w3schools.com/php/php_ajax_php.asp