skip to Main Content

I’m new to javascript and PHP. I was implementing recaptcha in my project. here is my code. I use preventDefault(); to prevent form from submitting and then I checked if the user checked the recaptcha and then submit the form again using form.submit(); But PHP code is not working.

Javascript :

 <script>
        form = document.getElementById("register-form");
        form.addEventListener('submit', (e) => {
            e.preventDefault();
            const captcha = grecaptcha.getResponse();
            if (!captcha.length > 0) {
                error = document.getElementById("error-msg");
                error.style.display = "block";
                console.log(error);
                error.innerHTML = "Failed!!Captcha Not Completed."
                throw Error("captcha not complete.");

            } else {
                form.submit();
            }
        })
    </script>

PHP:

<?php
include('database/connection.php');

if (isset($_POST['btnRegister'])) {

    #is set to check if the data is empty or not
    echo "test";

    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $password = $_POST['password'];
    $age = $_POST['age'];
    $gender = $_POST['gender'];
    $phone = $_POST['phone'];
    $email = $_POST['email'];
    $city = $_POST['city'];
    $country = $_POST['country'];

    $checkEmail = "Select Email from Customer where Email ='$email'";

    $result = mysqli_query(mysql: $connect, query: $checkEmail);

    if (mysqli_num_rows($result) == 0) {
        $insert = "Insert into Customer (Firstname,Surname,Age,Gender,Email,Password,Phone,City,Country)
    VALUES('$firstname','$lastname','$age','$gender','$email','$password','$phone','$city','$country')";

        $insertresult = mysqli_query(mysql: $connect, query: $insert);
        ($insertresult);
        if ($insertresult) {

            echo "<script>window.alert('Insert Success')</script>";


        } else {
            echo "<script>window.alert('Error')</script>";
        }

    } else {
        echo "<script>";
        echo "window.alert('Duplicate email')";
        echo "</script>";
    }


}




?>

2

Answers


  1. Chosen as BEST ANSWER

    I got it!! I only need to call preventDefault() only if the captcha fails. Here is my updated JS code.

    <script>
            form = document.getElementById("register-form");
            form.addEventListener('submit', (e) => {
          
                const captcha = grecaptcha.getResponse();
                if (!captcha.length > 0) {
                    e.preventDefault();
                    error = document.getElementById("error-msg");
                    error.style.display = "block";
                    console.log(error);
                    error.innerHTML = "Failed!!Captcha Not Completed."
                    throw Error("captcha not complete.");
    
                } 
            })
        </script>
    

  2. When you prevent the default form submission using e.preventDefault(); and then submit the form using JavaScript, the original triggering of the button does not occur. Therefore, the PHP if (isset($_POST[‘btnRegister’])) { … } is not being executed because btnRegister is not being set when the form is submitted via JavaScript.

    Here’s a potential solution to maintain the same logic:

    Solution:

    1. Change Your Button Type:

    Change your button type to button to avoid it submitting the form.

    <button type="button" id="btnRegister">Register</button>
    
    1. Add Event Listener to Button:

    Instead of adding an event listener to the form, you add it to the button. When the button is clicked, you manually check the captcha. If it’s valid, manually submit the form.

    <script>
        document.getElementById("btnRegister").addEventListener('click', (e) => {
            const captcha = grecaptcha.getResponse();
            if (!captcha.length > 0) {
                error = document.getElementById("error-msg");
                error.style.display = "block";
                console.log(error);
                error.innerHTML = "Failed!! Captcha Not Completed."
                return; // return here to stop the function execution.
            }
            document.getElementById("register-form").submit();
        })
    </script>
    
    1. Use Hidden Input:

    To check in PHP if the form has been submitted, you can use a hidden input field.

    <input type="hidden" name="formSubmitted" value="1">
    

    Then in PHP:

    if (isset($_POST['formSubmitted'])) {
        // your PHP code here
    }
    

    Updated PHP Check
    Now, instead of checking for the btnRegister, you check if the hidden input formSubmitted is set.

    if (isset($_POST['formSubmitted'])) {
        // Rest of your PHP Code
    }
    

    Summary:

    1. You’re using a button and JavaScript to manually submit the form.

    2. When the button is clicked, you’re checking the captcha and
      submitting the form via JavaScript if the captcha is valid.

    3. In PHP,
      you’re checking a hidden input to see if the form has been
      submitted.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search