Home » Php » html – Do I need 2 Send.php file for multiple ajax form submission

html – Do I need 2 Send.php file for multiple ajax form submission

Posted by: admin February 25, 2020 Leave a comment

Questions:

I successfully added a contact form to an html site following an example on line. I also used it PHPmailer to send mail. The form is submitted through ajax.
This is the form HTML code:

<div class="col-12 col-md-7">
    <form class="contact row" id="contact-form">
        <div class="form-group col-6">
            <input type="text" class="form-control" placeholder="Name" name="name" required="">
        </div>
        <div class="form-group col-6">
            <input type="email" class="form-control" placeholder="Email" name="email" required="">
        </div>
        <div class="form-group col-12">
            <input type="text" class="form-control" placeholder="Subject" name="subject" required="">
        </div>
        <div class="form-group col-12">
            <textarea class="form-control" placeholder="Message" name="message" required=""></textarea>
        </div>
        <div class="form-group col-12 mt-2">
            <button class="btn btn-primary">
                Send Message
            </button>
        </div>
    </form>
</div>

The in the website JS file, I added this:

$(function() {
    let loading = {
        show: function() {
            $("body").append("<div class='main-loading'></div>");
        },
        hide: function() {
            $(".main-loading").remove();
        }
    }

    $("#download-form").submit(function() {
        let $this = $(this);
        $.ajax({
            url: 'mail/send.php',
            type: "post",
            data: $this.serialize(),
            dataType: 'json',
            beforeSend: function() {
                loading.show();
            },
            complete: function() {
                loading.hide();
            },
            success: function(data) {
                if(data.status == true) {
                    swal("Success", data.data, "success");
                    $this[0].reset();
                }else{
                    swal("Failed", data.data, "error");
                }
            }
        });
        return false;
    });
});

In PHPMailer, I have this code:

<?php
//Import PHPMailer classes into the global namespace
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    require 'vendor/autoload.php';
    require 'config.php';

    $mail = new PHPMailer(true);
    try {
        //Server settings
        $mail->isSMTP();
        $mail->Host = $config['host'];
        $mail->SMTPAuth = true;
        $mail->Username = $config['username'];
        $mail->Password = $config['password'];
        $mail->SMTPSecure = $config['secure'];
        $mail->Port = $config['port'];

        //Recipients
        $mail->setFrom($config['from'], $config['fromName']);
        $mail->addAddress($config['sendTo']);
        $mail->addAddress($_POST['email']);

        //Content
        $mail->isHTML(true);
        $mail->Subject = 'Request for Brochure';
        $mail->Body    = '<p>First Name: ' . $_POST['firstname'] . "</p>"
        . "<p>Last Name: " . $_POST['lastname'] . "</p>"
        . "<p>Email: " . $_POST['email'] . "</p>"
        ;

        $mail->send();
        echo json_encode(['status' => true, "data" => 'Message has been sent']);
    } catch (Exception $e) {
        echo json_encode(['status' => false, "data" => "Message could not be sent\nMailer Error: " . $mail->ErrorInfo]);
    }
}else{
    echo "<h1>Access forbidden, kids!</h1>";
}

Now I am trying to add a second form to the page. My plan is to give it a different form ID i.e. #contact-form and then create a second send2.php and in the JS file, add this line :

$("#contact-form").submit(function() {
    let $this = $(this);
    $.ajax({
        url: 'mail/send2.php',
        type: "post",
        data: $this.serialize(),
        dataType: 'json',
        beforeSend: function() {
            loading.show();
        },
        complete: function() {
            loading.hide();
        },
        success: function(data) {
            if(data.status == true) {
                swal("Success", data.data, "success");
                $this[0].reset();
            }else{
                swal("Failed", data.data, "error");
            }
        }
    });
    return false;
});

I am just a basic PHP learning but I sense this is not an optimal way of doing it because I will be duplicating sends.php file when I want to add a new form. What is the way to combine this two codes on a single ‘send.php’ file?

How to&Answers: