Search code examples
javascriptphphtmlajaxforms

Form sent to twice using mail()


i am totally new in php and websites. I have issue on my website with form if somebody can help me?

Problem: whenever the user presses the send button, the form is sent twice and two emails arrive in the inbox. I assume something is triggering prigovor-submit.php twice but i can not find the reason.

This is my prigovor-submit.php code:

<?php

if ($_SERVER["REQUEST_METHOD"] === "POST") {
// Validate the form data
$errors = [];

// Prigovor Type (Radio Buttons)
if (!isset($_POST["prigovorType"]) || empty($_POST["prigovorType"])) {
    $errors[] = "Please select a type.";
}

// Full Name
$fullName = $_POST["fullName"];
if (empty($fullName)) {
    $errors[] = "Please enter your full name.";
} elseif (!preg_match("/^[A-Za-z\s]+$/", $fullName)) {
    $errors[] = "Invalid characters in the full name.";
}

$oib = $_POST["oib"];

// Email
$email = $_POST["email"];
if (empty($email) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors[] = "Please enter a valid email address.";
}

// Message
$message = $_POST["message"];

// Accept Policy
if (!isset($_POST["acceptPolicy"])) {
    $errors[] = "Please accept the privacy policy.";
}

$brUgovora = $_POST["brUgovora"];
$postalCode = $_POST["postalCode"];
$city = $_POST["city"];
$street = $_POST["street"];
$prigovorType = $_POST["prigovorType"];

if (empty($errors)) {
    $headers = "From: [email protected]\r\n";
    $headers .= "Reply-To: $email\r\n";
    $headers .= "Content-type: text/html\r\n";

    $to = "[email protected]"; // Replace with your email address
    $subject = "[Prigovor - ". $prigovorType ."] " . $oib;        
    $messageWithBreaks = str_replace(["\r\n", "\r", "\n"], '<br>', mb_convert_encoding($_POST["message"], 'HTML-ENTITIES', 'UTF-8'));
    $body = "<strong>Ime i prezime:</strong> $fullName<br>";
    $body .= "<strong>Email:</strong> $email<br>";
    $body .= "<strong>Broj predmet:</strong> $brUgovora<br>";
    $body .= "<strong>Tekst prigovora:</strong><br>$messageWithBreaks<br><br>";
    if (!empty($street) && !empty($postalCode) && !empty($city)) {
        $body .= "<strong>________________________________________________________________________________</strong><br>";
        $body .= "<strong>Adresa za dostavu odgovora:</strong> $street, $postalCode $city<br>";
        $body .= "<strong>________________________________________________________________________________</strong>";
    }
    // Send email
    if (mail($to, $subject, $body, $headers, '-f'. $email)) {
        // Email sent successfully
        echo json_encode(["status" => "success"]);
    } else {
        // Email sending failed
        echo json_encode(["status" => "error", "message" => "Failed to send email"]);

    }

    // Optionally, you can redirect the user to a thank you page
    // header("Location: thank-you.html");

    exit();
} else {
    // If there are errors, you might want to handle them appropriately.
    // For now, let's assume you want to output them as JSON.
    echo json_encode(["status" => "error", "errors" => $errors]);
    exit();
}
}

?>

This is my html:

        <div class="prigovor-container">
        <div class="popup-container" id="popupContainer">
            <div class="popup-box">
                <h1>Pozdrav!</h1>
                <p>Prigovor uspješno poslan!</p>
                <button class="close-btn" id="closeBtn">OK</button>
            </div>
        </div>
        <form id="myForm" class="needs-validation" novalidate action="prigovor-submit.php" method="post" enctype="multipart/form-data">
        <!-- Checkboxes -->
        <div class="form-group">
            <label>Vrsta otkupljenog potraživanja:*</label><br>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" id="radio3" name="prigovorType" value="Neprihodonosni kredit" required>
                <label class="form-check-label" for="radio3">Neprihodonosni kredit</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" id="radio4" name="prigovorType" value="Ostala potraživanja" required>
                <label class="form-check-label" for="radio4">Ostala potraživanja</label>
            </div>
        </div>

        <!-- Full Name -->
        <div class="form-group">
            <label for="fullName">Puno ime:*</label>
            <input type="text" class="form-control" id="fullName" placeholder="Unesite ime i prezime" required name="fullName">
        </div>

        <!-- OIB -->
        <div class="form-group">
            <label for="oib">OIB:*</label>
            <!-- <input type="text" class="form-control" id="oib" placeholder="Unesite Vaš OIB" required name="oib"> -->
            <input type="text" class="form-control" id="oib" placeholder="Unesite Vaš OIB (maksimalno 11 znamenki)" maxlength="11" pattern="[0-9]*" title="Unesite samo brojeve" required name="oib">

        </div>

        <!-- Email -->
        <div class="form-group">
            <label for="email">Adresa e-pošte:*</label>
            <input type="email" class="form-control" id="email" placeholder="Unesite adresu e-pošte" required name="email">
        </div>

        <!-- Broj ugovora -->
        <div class="form-group">
            <label for="brUgovora">Broj predmeta/ugovora:</label>
            <input type="brUgovora" class="form-control" id="brUgovora" placeholder="Unesite broj predmeta/ugovora" name="brUgovora">
        </div>

        <!-- Message Box -->
        <div class="form-group">
            <label for="message">Vaš prigovor napišite ovdje:</label>
            <textarea class="form-control" id="message" rows="3" placeholder="Unesite poruku" name="message" style="max-width: 100%; min-width: 100%;"></textarea>
        </div>

        <div class="form-group">
            <label>Želim dostavu odgovora:*</label><br>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" id="radio1" name="deliveryPreference" value="option1" required>
                <label class="form-check-label" for="radio1">putem e-pošte</label>
            </div>
            <div class="form-check form-check-inline">
                <input class="form-check-input" type="radio" id="radio2" name="deliveryPreference" value="option2" required>
                <label class="form-check-label" for="radio2">na adresu stanovanja</label>
            </div>
        </div>

        <div class="form-group" id="address" style="display:none;">
            <label for="address">Adresa stanovanja:*</label>
            <div class="address-cont">
                <div class="row">
                    <div class="col-md-6">
                        <input type="text" class="form-control" id="postalCode" placeholder="Poštanski broj" name="postalCode">
                    </div>
                    <div class="col-md-6">
                        <input type="text" class="form-control" id="city" placeholder="Grad" name="city">
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <input type="text" class="form-control" id="street" placeholder="Ulica i kućni broj" name="street">
                    </div>
                </div>
            </div>
        </div>


        <!-- File Attachment 
        <div class="form-group">
            <label for="attachment">Attachment (Accepted types: .doc, .docx, .pdf, .jpeg, .jpg, .png)</label>
            <input type="file" class="form-control-file" id="attachment" name="attachment">
        </div>-->

        <!-- Accept Policy -->
        <div class="form-group form-check">
            <input type="checkbox" class="form-check-input" id="acceptPolicy" required name="acceptPolicy">
            <label class="form-check-label" for="acceptPolicy">Pročitao/pročitala sam i <a href="https://website.com/pravila-privatnosti.php" target="_blank" tabindex="0">prihvaćam politiku privatnosti</a>.*</label>
        </div>

        <!-- Submit Button -->
        <!--<button type="submit" class="show-popup">Submit</button>-->
        <button type="submit" class="btn submit" id="submitBtn">Pošalji</button>
        
        </form>
    </div>


 <script src="form-validation.js" defer></script>
 <script src="popupscript.js"></script> 

And this is my popupscript.js:

document.addEventListener('DOMContentLoaded', function() {
const popupContainer = document.querySelector('.popup-container');
const closeBtn = document.querySelector('.close-btn');

// Function to show the popup
function showPopup() {
    popupContainer.classList.add('active');
}

// Function to close the popup
function closePopup() {
    popupContainer.classList.remove('active');
}

// Close button click event
closeBtn.onclick = closePopup;

// Form submit event
document.getElementById('myForm').addEventListener('submit', function(event) {
    event.preventDefault(); // Prevent the default form submission

    // Fetch data from the form
    const formData = new FormData(this);

    // Make an AJAX request to prigovor-submit.php
    fetch('prigovor-submit.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        // Check if the form submission was successful
        if (data.status === 'success') {
            // Display the popup
            showPopup();
        } else {
            // Handle errors if needed
            console.error('Form submission failed:', data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
    });
});
});

Code from form-validation.js:

document.addEventListener('DOMContentLoaded', function() {
const form = document.getElementById('myForm');

form.addEventListener('submit', function(event) {
    if (!form.checkValidity()) {
        event.preventDefault();
        event.stopPropagation();
    }

    form.classList.add('was-validated');
});

// Additional custom validation logic can be added here
   });


const radio1 = document.getElementById('radio1');
const radio2 = document.getElementById('radio2');
const addressDiv = document.getElementById('address');
const addressInput = document.getElementById('address');
const postalInput = document.getElementById('postalCode');
const cityInput = document.getElementById('city');
const streetInput = document.getElementById('street');

// Add an event listener to the radio buttons
radio1.addEventListener('change', toggleAddress);
radio2.addEventListener('change', toggleAddress);

// Function to toggle the visibility and required status of additionalInfo div
function toggleAddress() {
    addressDiv.style.display = radio2.checked ? 'block' : 'none';
    addressInput.required = radio2.checked;
    postalInput.required = radio2.checked;
    cityInput.required = radio2.checked;
    streetInput.required = radio2.checked;
}

Solution

  • Script below was called twice on different lines and that caused double trigger.

    <script src="popupscript.js"></script>