1

私は、David Powers の著書「PHP Solutions」で PHP を学んでいます。この本には、基本的な検証/エラー処理と入力サニタイズを備えた連絡フォームがあり、ページを更新せずに使用したいと考えています。

私はこれを XAMPP でローカルにテストしており、php フォーム自体を使用すると完全に機能します。エラー メッセージが正しく表示され、フォームが正常に送信されると、ありがとうページが表示され、フォームがテスト メール アドレスにメールとして配信されます。 .

ここで、AJAX を使用してエラー メッセージを送信および表示するためのフォームが必要です。これを達成するための多くの投稿を読みましたが、これを実装することに失敗しました。jQuery の $.ajax メソッドと $.post メソッドの両方を試しました。フィールドがすべて入力されている場合、成功メッセージが表示されますが、メッセージは送信されません。

私の推測では、javascript と php の配列は異なる構造になっていますが、これを調整する方法がわかりません。PHP処理スクリプトが何を取得/送信しているのかさえわかりません。ページを更新せずに、サーバー側の検証に php スクリプトを使用して、このフォームを送信するにはどうすればよいですか?

簡単にするために、私は自分のページから他のすべてを取り除きました (そして、すべてのファイルを同じフォルダーに入れました)。ただし、フォーム: php、html、および私が理解できない jQuery/AJAX を除きます。

これが理にかなっていることを願っています。私の4つのファイル:

mySite.js (私が問題を抱えている jQuery/AJAX...):

mySite = {

    jsFormSubmission : function() {
        $("#feedback").submit(function(event){
            event.preventDefault();
            var errorMsg = "<p class=\"errorBox\">Please fix the item(s) indicated.</p>";
            var successMsg = "<p class=\"messageBox\">Thanks for the submission, your message has been sent.</p>";

            var myObject = {
                name : $("#name").val(),
                email : $("#email").val(),
                comments : $("#comments").val()
            };

            var ajaxData = JSON.stringify(myObject);

            $.ajax({
                type: 'POST',
                url: 'form.php',
                data: ajaxData,
                success: function(data){
                    $(".formResult").html(successMsg);
                },
                error: function(http) {
                    $(".formResult").html(errorMsg);
                    alert(http.responseText);
                }
            });
        });
    }

};

フォーム (contact.php):

<?php include("form.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src=" mySite.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            mySite.jsFormSubmission();
        });
    </script>
</head>

<body>
    <div id="contact">

        <p class="formResult"></p>

        <?php $errorForm = (($_POST && $suspect) || ($_POST && isset($errors['mailfail'])));
              $errorTag = $missing || $errors;
              if ($errorForm || $errorTag) { ?>

        <p class="errorBox">
        <?php } ?>
            <?php if ($errorForm) { ?>
                Sorry, your message could not be sent. Please try again later.
                <?php  } elseif ($errorTag) { ?>
                Please fix the item(s) indicated.
            <?php } ?>
        <?php if ($errorForm || $errorTag) { ?>
        </p>
        <?php } ?>

        <form id="feedback" method="post" action="">

            <div class="tag">
                <label id="lblName" for="name">Name: 
                <?php if ($missing && in_array('name', $missing)) { ?>
                    <span style="color:red; font-weight:bold;">Please enter your name</span>
                <?php } ?>
                </label>
                <input name="name" id="name" type="text" class="formbox"
                <?php if ($missing || $errors) {
                    echo 'value="' . htmlentities($name, ENT_COMPAT, 'UTF-8') . '"';
                } ?>>
            </div>

            <div class="tag">
                <label id="lblEmail" for="email">Email: 
                <?php if ($missing && in_array('email', $missing)) { ?>
                    <span style="color:red; font-weight:bold;">Please enter your email address</span>
                <?php } elseif (isset($errors['email'])) { ?>
                    <span style="color:red; font-weight:bold;">Invalid email address</span>
                <?php } ?>
                </label>
                <input name="email" id="email" type="text" class="formbox"
                <?php if ($missing || $errors) {
                    echo 'value="' . htmlentities($email, ENT_COMPAT, 'UTF-8') . '"';
                } ?>>
            </div>

            <div class="tag">
                <label id="lblComments" for="comments">Comments: 
                <?php if ($missing && in_array('comments', $missing)) { ?>
                    <span style="color:red; font-weight:bold;">Please enter your message</span>
                <?php } ?>
                </label>
                <textarea name="comments" id="comments" cols="60" rows="8"><?php 
                    if ($missing || $errors) {
                        echo htmlentities($comments, ENT_COMPAT, 'UTF-8');
                    } ?></textarea>
            </div>

            <p>
                <input name="send" id="send" type="submit" value="Send message">
            </p>

        </form>
    </div>
    </body>
</html>

form.php (contact.php の上部に含まれています):

<?php 
$name = '';
$email = '';
$comments = '';
$required = '';
$errors = array();
$missing = array();
// check if the form has been submitted
if (isset($_POST['send'])) {
    //email processing script
    $to = 'johntest2@localhost';
    $subject = 'Website contact form';
    //list expected fields
    $expected = array('name', 'email', 'comments');
    // set required fields
    $required = array('name', 'email', 'comments');
    $headers = "From: Website Contact Test<johntest1@localhost>\r\n";
    $headers .= 'Content-Type: text/plain; charset=utf-8';

    require('processmail.php');
    if ($mailSent) {
        header("Location: thankYou.php#main");
        $messageConfirm = true;
        exit;
    }
}
?>

processmail.php (検証スクリプト - form.php に含まれています):

<?php

$suspect = false;
$pattern = '/Content-Type:|Bcc:|Cc:/i';

// function to check for suspect phrases
function isSuspect($val, $pattern, &$suspect) {
    if (is_array($val)) {
        foreach ($val as $item) {
            isSuspect($item, $pattern, $suspect);
        }
    } else {
        if (preg_match($pattern, $val)) {
            $suspect = true;
        }
    }
}
isSuspect($_POST, $pattern, $suspect);

if (!$suspect) {
    foreach ($_POST as $key => $value) {
        $temp = is_array($value) ? $value : trim($value);
        if (empty($temp) && in_array($key, $required)) {
            $missing[] = $key;
        } elseif (in_array($key, $expected)) {
            ${$key} = $temp;
        }
    }
}

// validate the user's email
if (!$suspect && !empty($email)) {
    $validemail = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
    if ($validemail) {
        $headers .= "\r\nReply-To: $validemail";
    } else {
            $errors['email'] = true;
    }
}

$mailSent = false;

if (!$suspect && !$missing && !$errors) {

    // initialize the $message variable
    $message = '';
    foreach($expected as $item) {
        if (isset(${$item}) && !empty(${$item})) {
            $val = ${$item};
        } else {
            $val = 'Not selected';
        }
        if (is_array($val)) {
            $val = implode(', ', $val);
        }
        $item = str_replace(array('_', '-'), ' ', $item);
        $message .= ucfirst($item).": $val\r\n\r\n";
    }

    $message = wordwrap($message, 70);

    $mailSent = mail($to, $subject, $message, $headers);
    if (!$mailSent) {
        $errors['mailfail'] = true;
    }
}
4

1 に答える 1

1

PHP 側からエラーを表示するには、いくつかの方法があります。お勧めしませんが、例外をスローするか、ヘッダーを使用できます。

header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);

AJAX 呼び出しで、jQuery エラー コールバックを使用します。

$.ajax({ 
    url: //url,
    data: //data,
    success: function (data) { //show success },
    error: function () { //display code here } 
});

PHP 側からエラー メッセージの本文でエラーを返し、エラー コールバックの本文からそれを削除することもできます。

PHP:

header($_SERVER['SERVER_PROTOCOL'] . ' 500 Internal Server Error', true, 500);
echo 'Your error message';

JavaScript:

error: function(http) {
   // show http.responseText;
}

また、フォーム送信のために、データをオブジェクトにパックしてからシリアル化します。そう:

var myObject = {
    property1 : 'string',
    property2 : [ 'array' ]
};

var ajaxData = JSON.stringify(myObject);
于 2013-02-12T15:42:45.003 に答える