Как автоматически заполнить выпадающее меню на странице формы, щелкнув ссылку на отдельной странице с помощью PHP - PullRequest
0 голосов
/ 23 октября 2019

Таким образом, у меня есть две страницы, одна из которых является страницей contact.php, в которой есть входные данные формы и т. Д. Другая страница - index.php, где у меня есть ссылки, которые ведут на страницу contact.php.

Я пытаюсь автоматически заполнить раскрывающееся меню на странице контактов после нажатия на одну из ссылок на странице индекса. Допустим, вы нажали «Ссылка А», после чего он должен перенаправить вас на страницу контактов, выбрав «Ссылка А» в раскрывающемся меню.

Я пытался использовать строки запроса в моем URL, например: "URL? Отдела = Доставка% 20Department", и я считаю, что я делал это правильно, но так как я не использую GET для своей формы, это нене работает?

В конце концов, форма должна иметь возможность отправить электронное письмо после отправки, которое я все выяснил, это просто автозаполнение, которое застряло у меня.

В моем листе назначения указано, что «у вас также будет страница контактов, которая отправляет строку запроса на страницу почты для автоматического заполнения поля отдела»

Ниже приведено то, что у меня есть для каждого из них. стр. Кроме того, извините заранее, это мой первый класс PHP, так что большая часть из уроков, и это может быть простая ошибка, которую я не вижу.

Index.php

<?php
include('includes/validate.php');
include('includes/mail.php');

?>
<!doctype html>
<html class="no-js" lang="">

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <style>
        .form-send {
          width: 100%;
          max-width: 400px;
          padding: 15px;
          margin: 0 auto;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>Contact Us</h1>

        <a href="contact.php">Shipping Department</a>
        <br/><br/>
        <a href="contact.php">Billing Inquiries</a>
        <br/><br/>
        <a href="contact.php">Party Planning Committee</a>

    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

Это без всех html-ссылок со строками запроса.

Contact.php

<?php
include('includes/validate.php');
include('includes/mail.php');
$hasMailErrors = false;
$hasFormErrors = false; 
$isSentMail = false;


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $reply_to_email = validate_email($_POST['email']);
    $reply_to_name = validate_string($_POST['name']);
    $department = validate_string($_POST['department']);
    $message_subject = validate_string($_POST['message-subject']);
    $message_body = validate_string($_POST['message-body']);

    if ($reply_to_email != false &&
        $reply_to_name != false &&
        $department != false &&
        $message_subject != false &&
        $message_body != false) {

          $isSentMail = send_custom_mail (
            $reply_to_email,
            $reply_to_name,
            $department,
            $message_subject,
            "To Whom It May Concern, <br/> <br/>"
            .$message_body.
            "<br/> <br/> Sincerely, <br/> <br/>"
            .$reply_to_name."<br>".$reply_to_email
          );

          if ($isSentMail) {
            $hasMailErrors = true;
          }

        } else {
          $hasFormErrors = true;
        }

    //validate
}
?>
<!doctype html>
<html class="no-js" lang="">

<head>
    <meta charset="utf-8">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <style>
        .form-send {
          width: 100%;
          max-width: 400px;
          padding: 15px;
          margin: 0 auto;
        }
    </style>
</head>

<body>
    <div class="container">

        <div class="text-center">
            <?php if (!$isSentMail) {?>
            <form class="form-send" method='post' action='<?php echo $_SERVER['PHP_SELF']; ?>'>
                <?php if ($hasFormErrors) { ?>
                <div class="alert alert-danger" role="alert">
                There was an error with the form
                </div>
                <?php } ?>

                <div class="form-input">
                    <label for="name">Name</label>
                    <input type="text" class="form-control" id="name" name="name" placeholder="name">
                </div>

                <div class="form-input">
                    <label for="email-field">Email address</label>
                    <input type="email" class="form-control" id="email-field" name="email" placeholder="name@example.com">
                </div>

                <div class="form-input">
                    <label for="department">Department</label>    
                    <select name="department" class="form-control" id="department">

                        <option selected="selected" value="Shipping Department">Shipping Department</option>

                        <option selected="selected" value="Billing Inquiries">Billing Inquiries</option>

                        <option selected="selected" value="Party Planning Committee">Party Planning Committee</option>

                    </select>
                </div>

                <div class="form-input">
                    <label for="subject">Subject</label>
                    <input type="text" class="form-control" id="subject" name="message-subject" placeholder="subject">
                </div>

                <div class="form-input">
                <label for="message-body">Enter Message Below</label>
                <textarea name="message-body" class="form-control" id="message-body" rows="3" placeholder="enter your message"></textarea>
                </div>

                <button class="submit-button" type="submit">Send</button>
            </form>
            <?php } else { ?>
            <h1>Thank you!</h1>
            <?php } ?>

        </div>

    </div>

    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

Тогда у меня есть мои включения для почты и проверки ...

Mail.php

<?php

require __DIR__.'/../vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function send_custom_mail($reply_to_email, $reply_to_name, $department, $subject, $message_body) {
    $gmail_username = "";
    $gmail_password = "";
    $gmail_name = "";

    $mailDebug = false;

    $mail = new PHPMailer(); 


    $mail->CharSet = "utf-8";
    $mail->IsSMTP(); 
    $mail->SMTPAuth = true; 


    $mail->Username = $gmail_username;
    $mail->Password = $gmail_password;

    $mail->SMTPSecure = "tls"; 

    if ($mailDebug) {
        $mail ->SMTPDebug = 2;
    }


    $mail->Host ="smtp.gmail.com";
    $mail->Port = "587";

    $mail->From = $gmail_username;
    $mail->FromName = $reply_to_name;


    $mail->AddReplyTo($reply_to_email, $reply_to_name);


    $mail->AddAddress($gmail_username, $gmail_name);


    $mail->IsHTML(true);
    $mail->Subject = $department.' - '.$subject;
    $mail->Body = $message_body;


    if ($mail->Send()) {

        return true;

    } else {


        if ($mailDebug) {
            echo $mail->ErrorInfo;
        }
        return false;

    }
}

Validate.php

<?php

function validate_email($email) {
    $email = filter_var($email, FILTER_SANITIZE_EMAIL); 
    $email = filter_var($email, FILTER_VALIDATE_EMAIL);
    return $email;
}

function validate_string($string) {
    $string = filter_var($string, FILTER_SANITIZE_STRING);

    if ($string === "") {
        return false;
    }
    return $string;
}

Ответы [ 2 ]

0 голосов
/ 23 октября 2019

Если вы измените HTML-код на странице index следующим образом:

<a href="contact.php?department=shipping">Shipping Department</a>
<a href="contact.php?department=billing">Billing Inquiries</a>
<a href="contact.php?department=planning">Party Planning Committee</a>

, а затем на странице contact измените структуру элемента select следующим образом:

<select name="department" class="form-control" id="department">
    <option value='error' selected hidden disabled>Please select
    <?php

        /* possible departments that might be selected by clicking hyperlink elsewhere */
        $departments=[
            'shipping'  =>  'Shipping Departmen',
            'billing'   =>  'Billing Inquiries',
            'planning'  =>  'Party Planning Committee'
        ];

        /* filter querystring variable, remove junk and force lowercase */
        $department=strtolower( trim( urldecode( filter_input( INPUT_GET, 'department', FILTER_SANITIZE_STRING ) ) ) );


        /* 
            process all the departments and add an `option` to the `select` menu
            - identifying if it is selected or not in the process.
        */
        foreach( $departments as $key => $value ){
            $selected = ( $department && $key === $department ) ? ' selected' : '';
            printf('<option value="%1$s"%2$s>%1$s', $value, $selected );
        }
    ?>
</select>

Добавляя selected hidden disabled к исходному option в меню select, вы гарантируете, что пользователь видит меню и должен выбрать из него какой-либо параметр, а не полагаться на первый параметр вменю выбирается по умолчанию. Если пользователь изменяет переменную строки запроса для значения, которое не отображается в ключах массива отделов, то этот Please Select будет снова отображаться, а значение error будет отправлено при отправке формы.

Одно замечание: не используйте $_SERVER['PHP_SELF'] в качестве действия формы - просто полностью пропустите действие, если сценарий должен сам POST, поскольку $_SERVER['PHP_SELF'] уязвим для перехвата.

0 голосов
/ 23 октября 2019

Пожалуйста, обновите ссылки в index.php как показано ниже,

<a href="contact.php?department=Shipping Department">Shipping Department</a>

<a href="contact.php?department=Billing Inquiries">Billing Inquiries</a>

<a href="contact.php?department=Party Planning Committee">Party Planning Committee</a>

и измените параметры в contact.php следующим образом:

<?php $department = isset($_GET['department']) ? $_GET['department'] : "Shipping Departmen"; ?>

<option <?php if ($department == "Shipping Department"): ?>selected="selected"<?php endif; ?> value="Shipping Department">Shipping Department</option>

<option <?php if ($department == "Billing Inquiries"): ?>selected="selected"<?php endif; ?> value="Billing Inquiries">Billing Inquiries</option>

<option <?php if ($department == "Party Planning Committee"): ?>selected="selected"<?php endif; ?> value="Party Planning Committee">Party Planning Committee</option>

Это должно работать, если оба файла находятся втот же каталог.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...