skip to Main Content

I need some help. I try to do registration and because I need to refresh only the registration part on page, I must use ajax. And here is the problem. When I submit the form, ajax loads different file, where is registration part in php. In php I have some variables, which I use to change color of particular inputs, if there was an error. But, because the php is in other file, I cant access the variables from file, where the ajax is and change the colors. And if I try place script, which changes the colors, in the file, where php is, it dont execute, because I somewhere stop php with for example “return false”.

Do you know please, what I can do with this? Thank you very much and sorry for my bad english.

This is the ajax part

<script>

        $(document).ready(function(){

            $("#registerUser").submit(function(event){
                event.preventDefault();
                var typedEmail = $("#registerEmail").val(),
                typedPassword = $("#registerPassword").val(),
                typedRepeatedPassword = $("#registerRepeatedPassword").val();
                submittedForm = $("#registerSubmit").val();

                $("#registerMessage").load("accountRegistration.php", {
                    email: typedEmail,
                    password: typedPassword,
                    repeatedPassword: typedRepeatedPassword,
                    submit: submittedForm
                });

            });

        });

    </script>

This is the php file

if(isset($_POST["submit"])){
    require_once "autoload.php";

    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $password = $_POST["password"];
    $repeatedPassword = $_POST["repeatedPassword"];
    $emailError = false;
    $passwordError = false;
    $repeatedPasswordError = false;

    if(empty($email)){
      $emailError = true;
    }

    if(empty($password)){
      $passwordError = true;
    }

    if(empty($repeatedPassword)){
      $repeatedPasswordError = true;
    }

    if(strlen($password) < 8){
      $passwordError = true;
    }

    if($password != $repeatedPassword){
      $repeatedPasswordError = true;
    }

    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
      $emailError = true;
    }

    if($emailError == true || $passwordError == true || $repeatedPasswordError == true){
      echo("<span class='errorMessage'>Vyplňte správně všechna políčka!</span>");
      return false;
    }

    $registration = new DatabaseOperations;
    if($registration->selectOneRow("users", "userID", "email", $email, PDO::PARAM_STR)){
      echo("<span class='errorMessage'>Tento email už někdo používá.</span>");
      return false;
    }

    $passwordHash = password_hash($password, PASSWORD_DEFAULT);
    if($registration->insertOneRow("users", array("email", "password"), array($email, $passwordHash))){
      echo("<span class='successMessage'>Registrace proběhla úspěšně.</span>");
      return true;
    } else{
      echo("<span class='errorMessage'>Něco se pokazilo. Zkuste to prosím znovu.</span>");
      return false;
    }



  } else{
    echo ("Stala se chyba. Zkuste to prosím znovu.");
  }

<script>

$("#registerEmail, #registerPassword, #registerRepeatedPassword").removeClass("inputError");

var emailError = "<?php echo(isset($emailError) ? $emailError : '') ?>";
var passwordError = "<?php echo(isset($registerPassword) ? $registerPassword : '') ?>";
var repeatedPasswordError = "<?php echo(isset($registerRepeatedPassword) ? $registerRepeatedPassword : '') ?>";
console.log(emailError);
console.log(passwordError);
console.log(repeatedPasswordError);

if(emailError == true){
  $("#registerEmail").addClass("inputError");
}

if(passwordError == true){
  $("#registerPassword").addClass("inputError");
}

if(repeatedPasswordError == true){
  $("#registerRepeatedPassword").addClass("inputError");
}

if(passwordError == true || repeatedPasswordError == true){
  $("#registerPassword").val("");
  $("#registerRepeatedPassword").val("");
}

</script>

And here is the HTML

<div class="signUp">
            <h1>registrace</h1>
            <form method='POST' name="register" id="registerUser">
                <p id="registerMessage"></p>
                <input type='email' id='registerEmail' name='email' placeholder='Váš email'>
                <input type='password' id='registerPassword' name='password' placeholder='Vaše heslo (min. 8 znaků)'>
                <input type='password' id='registerRepeatedPassword' name='repeatedPassword' placeholder='Ověření hesla'>
                <input type='submit' id='registerSubmit' name='' value='REGISTROVAT'>
            </form>
            <p>MÁM ÚČET A&nbsp;<a href="#null"  class="changeForm">CHCI SE PŘIHLÁSIT</a><p>
        </div>

2

Answers


  1. Chosen as BEST ANSWER

    Ajax with html does the same. It returns only what is in "echo"

    $.ajax({
                        method: "POST",
                        url: "accountRegistration.php",
                        data: {
                            email: typedEmail,
                            password: typedPassword,
                            repeatedPassword: typedRepeatedPassword,
                            submit: submittedForm
                        },
                        dataType: "html",
                        success: function(errors){
                            console.log("Errors: " + errors);
                        }
                    })
    

  2. Finally, I did it like this..

    <script>
    
            $(document).ready(function(){
    
                $("#registerUser").submit(function(event){
                    event.preventDefault();
                    var typedEmail = $("#registerEmail").val(),
                    typedPassword = $("#registerPassword").val(),
                    typedRepeatedPassword = $("#registerRepeatedPassword").val();
                    submittedForm = $("#registerSubmit").val();
    
                    $.ajax({
                        method: "POST",
                        url: "accountRegistration.php",
                        data: {
                            email: typedEmail,
                            password: typedPassword,
                            repeatedPassword: typedRepeatedPassword,
                            submit: submittedForm
                        },
                        dataType: "json",
                        success: function(results){
    
                            $("#registerMessage").html(results["message"]);
    
                            $("#registerEmail, #registerPassword, #registerRepeatedPassword").removeClass("inputError");
    
                            var emailError = results["emailError"];
                            var passwordError = results["passwordError"];
                            var repeatedPasswordError = results["repeatedPasswordError"];
    
                            if(emailError == true){
                              $("#registerEmail").addClass("inputError");
                            }
    
                            if(passwordError == true){
                              $("#registerPassword").addClass("inputError");
                            }
    
                            if(repeatedPasswordError == true){
                              $("#registerRepeatedPassword").addClass("inputError");
                            }
    
                            if(passwordError == true || repeatedPasswordError == true){
                              $("#registerPassword").val("");
                              $("#registerRepeatedPassword").val("");
                            }
    
                        }
                    });
    
                });
    
            });
    
        </script>
    
    
    
    
    <?php
      if(isset($_POST["submit"])){
        registerUser();
      }
    
      function registerUser(){
        require_once "autoload.php";
    
        $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
        $password = $_POST["password"];
        $repeatedPassword = $_POST["repeatedPassword"];
        $emailError = false;
        $passwordError = false;
        $repeatedPasswordError = false;
    
        if(empty($email)){
          $emailError = true;
        }
    
        if(empty($password)){
          $passwordError = true;
        }
    
        if(empty($repeatedPassword)){
          $repeatedPasswordError = true;
        }
    
        if(strlen($password) < 8){
          $passwordError = true;
        }
    
        if($password != $repeatedPassword){
          $repeatedPasswordError = true;
        }
    
        if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
          $emailError = true;
        }
    
        if($emailError == true || $passwordError == true || $repeatedPasswordError == true){
          echo (json_encode(
            array("emailError" => $emailError,
             "passwordError" => $passwordError,
             "repeatedPasswordError" => $repeatedPasswordError,
             "message" => "<span class='errorMessage'>Vyplňte správně všechna políčka!</span>"
            )));
          return false;
        }
    
        $registration = new DatabaseOperations;
        if($registration->selectOneRow("users", "userID", "email", $email, PDO::PARAM_STR)){
          echo(json_encode(array("message" => "<span class='errorMessage'>Tento email už někdo používá.</span>")));
          return false;
        }
    
        $passwordHash = password_hash($password, PASSWORD_DEFAULT);
        if($registration->insertOneRow("users", array("email", "password"), array($email, $passwordHash))){
          echo(json_encode(array("message" => "<span class='successMessage'>Registrace proběhla úspěšně.</span>")));
          return true;
        } else{
          echo(json_encode(array("message" => "<span class='errorMessage'>Něco se pokazilo. Zkuste to prosím znovu.</span>")));
          return false;
        }
    
      }
    
     ?>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search