Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

Need help fixing Contact Forms (html + jscript + php)

Is there anyone that's experienced with html/css that can help me make some minor fixes to finish off my website?

I used AI to create a website for my onlyfans agency, but the contact forms don't work properly. I'm trying to get them to function using sweetalerts, and redirect to the homepage, unless they're already on the homepage in which case it only clicks off of the sweetalert and stays on the homepage.

Currently, the issue I'm facing is after submitting a form the sweetalert pops up and works only once, but if I go to another page and submit the other forms or even the original one I did it'll stop giving the sweetalert and go to a white error page instead.

I have one jscript file, one php file, one css file, and html files for three different pages with contact forms, two of which are only contact forms.

Here's what I have for my jscript:

Code
document.getElementById('contactForm').onsubmit = function(event) {
    event.preventDefault(); // Prevent the default form submission

    var formData = new FormData(this); // Collect form data
    var xhr = new XMLHttpRequest();

    xhr.open('POST', '/send_message.php', true); // Ensure URL matches your PHP script location

    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 400) {
            var response = JSON.parse(xhr.responseText);
            if (response.status === 'success') {
                // Show success message using SweetAlert2
                Swal.fire({
                    icon: 'success',
                    title: 'Success!',
                    text: response.message,
                    timer: 2000, // Auto-close after 2 seconds
                    showConfirmButton: false
                }).then(() => {
                    window.location.href = '/index/'; // Redirect to /index/ after success message
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Oops...',
                    text: response.message
                });
            }
        } else {
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An error occurred while processing the request.'
            });
        }
    };

    xhr.onerror = function() {
        Swal.fire({
            icon: 'error',
            title: 'Error',
            text: 'An error occurred while processing the request.'
        });
    };

    xhr.send(formData);
};

send_message.php
Code
<?php
// Enable error reporting for debugging
error_reporting(E_ALL);
ini_set('display_errors', 1);

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $response = [
        "status" => "error",
        "message" => "An unexpected error occurred. Please try again later."
    ];

    // Capture form data with validation
    $name = isset($_POST['name']) ? htmlspecialchars($_POST['name'], ENT_QUOTES, 'UTF-8') : '';
    $email = isset($_POST['email']) ? filter_var($_POST['email'], FILTER_SANITIZE_EMAIL) : '';
    $subject = isset($_POST['subject']) ? htmlspecialchars($_POST['subject'], ENT_QUOTES, 'UTF-8') : '';
    $message = isset($_POST['message']) ? htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8') : '';

    // Validate email format
    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $response = [
            "status" => "error",
            "message" => "Invalid email address."
        ];
        echo json_encode($response);
        exit();
    }

    // File upload handling
    $fileStatus = "No file uploaded.";
    if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
        $file = $_FILES['file'];
        $uploadDir = 'uploads/';
        $uploadFile = $uploadDir . basename($file['name']);
        
        if (!is_dir($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }

        if (move_uploaded_file($file['tmp_name'], $uploadFile)) {
            $fileStatus = "File uploaded successfully.";
        } else {
            $fileStatus = "Failed to move uploaded file.";
        }
    } elseif (isset($_FILES['file'])) {
        $fileStatus = "File upload error: " . $_FILES['file']['error'];
    }

    // Email configuration
    $to = "[email protected]"; // Replace with your email address
    $headers = "From: $email";
    $body = "Name: $name\nEmail: $email\nSubject: $subject\nMessage: $message\n\n" . $fileStatus;

    // Try to send the email
    if (mail($to, $subject, $body, $headers)) {
        $response = [
            "status" => "success",
            "message" => "Message sent successfully!"
        ];
    }

    // Send JSON response
    header('Content-Type: application/json');
    echo json_encode($response);
    exit();
}
?>

Then here's the code for just the contact form on my index for reference:

Code
<div class="contact">
                <h2><i class="fa-solid fa-envelopes-bulk" style="color: #8755b3;"></i> Contact</h2>
                <form id="contactForm" action="/send_message.php" method="POST">
                    <input type="text" placeholder="Name" id="name" name="name" required>
                    <input type="email" placeholder="Email" id="email" name="email" required>
                    <textarea id="message" placeholder="Message" name="message" required></textarea>
                    <button type="submit" class="submitbutton">Submit</button>
                </form>
            </div>

I've ran it through ChatGPT and Claude AI's both several times, no matter what changes they made the issue seemed to remain.
[Image: masterssig.png]
Can you maybe share a screen recording of what happens? I cant understand your problem
(Aug 23, 2024 08:54 PM)AngelArt Wrote:  Can you maybe share a screen recording of what happens? I cant understand your problem

I would but I'm unable to post any links or anything currently until my post count is higher, and I'd rather not post trash just for that
[Image: masterssig.png]
I was able to fix the contact forms. All of the code I had was essentially already working. The issue was that I modified my link path using .htaccess so I had to change the script load link to fit that, as well as add some required autocomplete= tags to some of my fields.

Somehow fixing this also fixed my headers scroll animation haha, two for two. Anyways, job completed on my own I feel rather accomplished.
[Image: masterssig.png]
(Aug 23, 2024 11:08 PM)Masters Wrote:  I would but I'm unable to post any links or anything currently until my post count is higher, and I'd rather not post trash just for that

Just engage with the community in the lounge and reply with actual thought behind it. You will be able to get help to your answer with a video.
[Image: Blockonome-Signature.jpg]
(Aug 25, 2024 08:07 AM)Blockonome Wrote:  Just engage with the community in the lounge and reply with actual thought behind it. You will be able to get help to your answer with a video.

It's fine I was able to solve the problem already not sure if you saw my last post above yours.
[Image: masterssig.png]


Possibly Related Threads...
Thread / Author Replies Views Last Post
by Account of the GodsJul 8, 2018 07:55 PM 2 147 Jul 8, 2018 07:55 PM
Last Post: Rasta
by GreenTeaJun 27, 2017 01:30 PM 5 144 Jun 27, 2017 01:30 PM
Last Post: Rushax
by priluxDec 10, 2016 11:18 AM 1 236 Dec 10, 2016 11:18 AM
Last Post: VirtualFrost