Hack Forums
Need help fixing Contact Forms (html + jscript + php) - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Webmasters (https://hackforums.net/forumdisplay.php?fid=141)
+---- Forum: Website Construction (https://hackforums.net/forumdisplay.php?fid=50)
+---- Thread: Need help fixing Contact Forms (html + jscript + php) (/showthread.php?tid=6278406)



Need help fixing Contact Forms (html + jscript + php) - Masters - Aug 23, 2024

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.


RE: Need help fixing Contact Forms (html + jscript + php) - AngelArt - Aug 23, 2024

Can you maybe share a screen recording of what happens? I cant understand your problem


RE: Need help fixing Contact Forms (html + jscript + php) - Masters - Aug 23, 2024

(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


RE: Need help fixing Contact Forms (html + jscript + php) - Masters - Aug 24, 2024

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.


RE: Need help fixing Contact Forms (html + jscript + php) - Blockonome - Aug 25, 2024

(Aug 23, 2024 11:08 PM)Matriix 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.


RE: Need help fixing Contact Forms (html + jscript + php) - Masters - Aug 25, 2024

(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.