【问题标题】:how do i submit a angular js built form to an email address我如何将 Angular js 构建的表单提交到电子邮件地址
【发布时间】:2015-02-25 23:15:14
【问题描述】:

我有以下使用角度的形式。我想将结果提交到一个电子邮件地址,并设置了一个带有服务器端代码的 php 操作页面来执行此操作。

但是,我在表单元素上使用action="action.php" 调用的方式感觉不对。实际上很脏......但我不确定还有其他方法。这是提交表格的最佳方式吗?我是否应该通过 ng-submit 使用 AJAX 调用来收集和存储数据......

这是表单的JSfiddle,但没有action="action.php" - 我正在尝试使用ng-submit="mealForm.$valid"

下面是我使用action="action.php" 的代码 - 你会看到我已经添加了动作调用并省略了ng-submit="mealForm.$valid",因为不确定这是如何工作的,即使在大量阅读docs 之后也是如此

非常感谢任何帮助 - 新手到 angular :)

谢谢

HTML

<!DOCTYPE html>
<html ng-app="form">
<head>
    <link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body>
<div class="container" style="margin-top: 40px;">
    <section ng-controller="PanelController as panel">
        <ul class="nav nav-pills">
            <li ng-class="{ active: panel.isSelected(1)}">
                <a href ng-click="panel.selectTab(1)">Standard Form</a>
            </li>
            <li ng-class="{ active: panel.isSelected(2)}">
                <a href ng-click="panel.selectTab(2)">Custom Form</a>
            </li>
        </ul>
        <div class="panel" ng-show="panel.isSelected(1)">
        <h4>Standard Form</h4>
        <p>Use the standard form if the number people and meals are the same throughout your stay.<br />E.G : 10 people wanting 7 dinners over a 7 day period.</p>
        <p>Use the custom form if the number of people wanting meals alters each day.</p>
        <p><span class="required">*</span> required fields</p>
        <form name="mealForm" ng-controller="FormController as form" action="action.php" method="post" novalidate>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label for="firstName">First Name<span class="required"> *</span></label>
                        <input ng-model="booking.firstName" type="text" class="form-control" id="firstName" name="firstName" placeholder="First Name" required>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label for="lastName">Last Name<span class="required"> *</span></label>
                        <input ng-model="booking.lastName" type="text" class="form-control" id="lastName" name="lastName" placeholder="Last Name" required>
                    </div>
                </div>  
            </div>

            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label for="email">Email<span class="required"> *</span></label>
                        <input ng-model="booking.email" type="email" class="form-control" id="email" name="email" placeholder="Email" required>
                     </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label for="telephone">Phone Number</label>
                        <input type="text" class="form-control" id="telephone" name="telephone" placeholder="Telephone" required>
                    </div>
                </div>  
            </div>

            <div class="row">
                <div class="col-sm-6">
                     <div class="form-group">
                        <label for="startDate">Start Date</label>
                        <input type="date" class="form-control" name="startDate" id="startDate" required>
                    </div>
                </div>
                <div class="col-sm-6">
                     <div class="form-group">
                        <label for="endDate">End Date</label>
                        <input type="date" class="form-control" name="endDate" id="endDate" required>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label for="totalDays">Number of Days <span class="required"> *</span><em>(Discount of 10% Applies for 10 or more days)</em></label>
                        <select ng-model="booking.totalDays" class="form-control" name="totalDays" id="totalDays"  required>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                                <option value="6">6</option>
                                <option value="7">7</option>
                                <option value="8">8</option>
                                <option value="9">9</option>
                                <option value="10">10</option>
                                <option value="11">11</option>
                                <option value="12">12</option>
                                <option value="13">13</option>
                                <option value="14">14</option>
                                <option value="15">15</option>
                                <option value="16">16</option>
                                <option value="17">17</option>
                                <option value="18">18</option>
                                <option value="19">19</option>
                                <option value="20">20</option>
                                <option value="21">21</option>
                                <option value="22">22</option>
                                <option value="23">23</option>
                                <option value="24">24</option>
                                <option value="25">25</option>
                                <option value="26">26</option>
                                <option value="27">27</option>
                                <option value="28">28</option>
                                <option value="29">29</option>
                                <option value="30">30</option>
                        </select>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label for="groupSize">Group Size <span class="required"> *</span><em>(max 15)</em></label>
                        <select ng-model="booking.groupSize" class="form-control" name="groupSize" id="groupSize" required>
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="5">5</option>
                                <option value="6">6</option>
                                <option value="7">7</option>
                                <option value="8">8</option>
                                <option value="9">9</option>
                                <option value="10">10</option>
                                <option value="11">11</option>
                                <option value="12">12</option>
                                <option value="13">13</option>
                                <option value="14">14</option>
                                <option value="15">15</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label>Meal Type <span class="required"> *</span><em>(Select from below options)</em></label>
                        <ul>
                            <li ng-repeat="meal in form.meals" ng-click="form.selectMeal(meal);" ng-class="{active:meal.active}" class="mealType">{{meal.name}} - {{meal.description}} <span>{{meal.price | currency}}</span>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="col-sm-6">
                    <div class="form-group">
                        <label for="message">Accomodation Details <em>(Please provide full address / specific dietery requirements and any other information)</em></label>
                        <textarea name="message" id="message"></textarea>
                    </div>
                </div>
            </div>
            <div class="form-group">
                <hr />
                <label for="total">
                    Total: <span>{{form.total(booking.totalDays, booking.groupSize)[0] | currency}}</span> <em ng-show="form.total(booking.totalDays, booking.groupSize)[3]">(10% Discount of <span>{{form.total(booking.totalDays, booking.groupSize)[1] | currency}} applied)</em></span>
                </label>
            </div>
            <div class="form-group">
                <div class="form-valid" ng-class="{active: mealForm.$valid}">Form complete: {{mealForm.$valid}}</div>
                <hr />
                <button type="submit" ng-disabled="mealForm.$invalid" value="Submit" class="btn btn-default">Submit</button>
            </div>

            <input type="hidden" name="mealType" value="{{form.total()[2]}}">   

            <input type="hidden" name="total" id="total" value="{{form.total(booking.totalDays, booking.groupSize)[0] | currency}}">

            <input type="hidden" name="discount" value="{{form.total(booking.totalDays, booking.groupSize)[1] | currency}}">    
        </form>
    </div><!-- /.panel -->
    <div class="panel" ng-show="panel.isSelected(2)">

    </div>
</section>
</div>

</body>
</html>

角度 JS (APP.JS) 已编辑

(function () {

var app = angular.module('form', []);
// start of edit
app.controller('FormController', ['$scope','$window',
    function($scope,$window){

    this.meals = mealTypes;

    $scope.handleFormSubmit = function (booking) {
        $http.post('action.php', booking).success(function (data, status) {
            if (data.success) {
                $window.alert("Thank you! Your message has been sent.");
            }
        }).error(function (data, status) {
            $window.alert("Sorry, there was a problem! " + data.message);
        });
    };

    // end of edit

    this.selectMeal = function (setMeal) {
        if (!setMeal.active) {
            angular.forEach(this.meals, function (s) {
                s.active = false;
            });
            setMeal.active = true;
        }
    };

    this.total = function (days, size) {
        var total = 0;
        var percentage = 0;
        var mealType;
        var discount = false;
        total = days * size;


        angular.forEach(this.meals, function (s) {
            if (s.active) {
                total *= s.price;
                mealType = s.name + ' - ' + s.description;
            }

        });
        if (days >= 10) {
            percentage = (total / 100) * 10;
            total -= percentage;
            discount = true;
        }

        return [total, percentage, mealType, discount];

    };

});

var mealTypes = [{
    name: 'breakfast',
    price: '20',
    description: 'Three course breakfast',
    active: true
}, {
    name: 'dinner',
    price: '20',
    description: 'Three course dinner',
    active: false
}, {
    name: 'both',
    price: '40',
    description: 'Breakfast and Dinner',
    active: false
}

];

app.controller('PanelController', function () {
    this.tab = 1;

    this.selectTab = function (setTab) {
        this.tab = setTab;
    };

    this.isSelected = function (checkTab) {
        return this.tab == checkTab;
    };
});
})();

PHP (ACTION.PHP)

<?php

if(isset($_POST['email'])) {



// EDIT THE 2 LINES BELOW AS REQUIRED

$email_to = "me@example.com";

$email_subject = "Subject line";





function died($error) {

    echo "We are very sorry, but there were error(s) found with the form you submitted. ";

    echo "These errors appear below.<br /><br />";

    echo $error."<br /><br />";

    echo "Please go back and fix these errors.<br /><br />";

    die();

}



$firstName = $_POST['firstName'];

$lastName = $_POST['lastName'];

$email_from = $_POST['email'];

$telephone = $_POST['telephone'];

$startDate = $_POST['startDate'];

$endDate = $_POST['endDate'];

$totalDays = $_POST['totalDays'];

$groupSize = $_POST['groupSize'];

$mealType = $_POST['mealType'];

$discount = $_POST['discount'];

$total = $_POST['total'];


$email_message = "Form details below.\n\n";


function clean_string($string) {

  $bad = array("content-type","bcc:","to:","cc:","href");

  return str_replace($bad,"",$string);

}



$email_message .= "First Name: ".clean_string($firstName)."\n";

$email_message .= "Last Name: ".clean_string($lastName)."\n";

$email_message .= "Email: ".clean_string($email_from)."\n";

$email_message .= "Telephone: ".clean_string($telephone)."\n";

$email_message .= "Start Date: ".clean_string($startDate)."\n";

$email_message .= "End Date: ".clean_string($endDate)."\n";

$email_message .= "Total Days: ".clean_string($totalDays)."\n";

$email_message .= "Group Size: ".clean_string($groupSize)."\n";

$email_message .= "Meal Type: ".clean_string($mealType)."\n";

$email_message .= "Discount: ".clean_string($discount)."\n";

$email_message .= "Total: ".clean_string($total)."\n";





// create email headers

$headers = 'From: '.$email_from."\r\n".

'Reply-To: '.$email_from."\r\n" .

'X-Mailer: PHP/' . phpversion();

@mail($email_to, $email_subject, $email_message, $headers);  

?>


Thank you for contacting us. We will be in touch with you very soon.

<?php

}

?>

【问题讨论】:

    标签: javascript php angularjs forms


    【解决方案1】:

    您可以在 AngularJS 中使用$http.post(...) 请求。这将允许您接收响应并显示成功消息,而无需重新加载页面。

    如果你想走这条路,我建议为每个字段添加一个ng-model="params.fieldName" 属性(只需更改fieldName 以匹配传递给PHP 表单的值)。然后在您的控制器中,您可以执行以下操作:

    $scope.handleFormSubmit = function (params) {
        $http.post('action.php', params).success(function (data, status) {
            if (data.success) {
                $window.alert("Thank you! Your message has been sent.");
            }
        }).error(function (data, status) {
            $window.alert("Sorry, there was a problem! " + data.message);
        });
    };
    

    然后在您的&lt;form ...&gt; 标签中,您可以执行以下操作:

    <form ng-submit="handleFormSubmit(params)" ...>
    

    然后在你的 PHP 脚本中,你只需要输出一个带有你想要传递给 AngularJS 的变量的 JSON 对象。

    <?php echo json_encode({success: false, message: "Couldn't send email"}); ?>
    

    最好不要使用$window.alert(...),而是显示某种内联消息。如果表单发送成功,您也可以将其隐藏以防止用户再次发送。您还应该对提交按钮进行一些操作,以在发送表单时禁用它,因此不能多次单击它。

    另外,您可以返回状态码,而不是从 PHP 返回值:

    <?php http_response_code(400); ?>
    

    如果在 200 范围内,它将激活 .success(...) 回调。如果它在 400 范围内,它将激活 .error(...) 回调。您可以查看what each status code means

    【讨论】:

    • 嗨,谢谢。使用上述方法,我得到一个错误说明范围未定义
    • @fidev 您必须在您的app.controller 中声明它,如下所示:app.controller('FormController', function ($scope, $window) { ... }。也许你应该从Code School - AngularJS Tutorial开始。
    • 再次感谢,是的,这就是我开始的地方以及我用来制作表格的地方,但对上一个视频中提到的发布位有点困惑 - 它只是将数据发布与电子邮件相结合它到一个让我头疼的地址......:S - 我会继续努力。
    • 我已经在输入上有 ng-models,例如 ng-model="booking.firstName" 所以调整了 handleFormSubmit 函数以及 ng-submit 以采用 'booking' 而不是 'params'。但是不确定在哪里添加您提到的 JSON sn-p。这包含正确的表单字段数组,或者不是..
    • 我已将 handleFormSubmit 函数添加到 app.js 并在 app.controller 中声明了范围。当我单击提交时,handleFormSubmit 函数正在触发,但我收到窗口警报 - '对不起,出现问题!未定义'
    【解决方案2】:

    对于提交,您可以单击 ng-click

     <input type="text" size="40" ng-model="email"><br>
     <input type="text" size="40" ng-model="msg"><br>
    <button type="submit" ng-disabled="mealForm.$invalid" ng-click="SendEmail()" value="Submit" class="btn btn-default">Submit</button>  
    

    接下来你需要发送一个 http 帖子

    $scope.SendEmail= function () {
    
    
                        var request = $http({
                            method: "post",
                            url: window.location.href + "send.php",
                            data: {
                                email: $scope.email,
                                msg: $scope.msg
                            },
                            headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                        });
    
                        /* Check whether the HTTP Request is successful or not. */
                        request.success(function (data) {
                            document.getElementById("message").textContent = "You send email successfully "+data;
    
    
                        });
                        }
    

    在 Send.php 中

      $postdata = file_get_contents("php://input");
        $request = json_decode($postdata);
        @$email= $request->email;
        @$msg = $request->msg;
    
    // all code for send email and next you can return a value if email is sending, with  return "Msg is Sending", and you can capture it in request.success
    

    PD:对于从 Php 到 Javascript 的返回值,仅使用 return value;,接下来您可以使用

    request.success(function (data) {... where data=value;
    

    【讨论】:

    • 嗨,我已将 SendEmail 函数添加到我的 app.js 中,但在控制台中出现“未定义 $scope”错误。我已将函数与 FormController 一起放置。我应该用“this.”替换“$scope”吗?
    • 并与 send.php 文件代码略有混淆。这就是我所需要的 - 我将我的电子邮件地址放在哪里,就像我拥有的​​ action.php 文件一样......?抱歉,我对这一切都很陌生...
    • $scope 必须在您的控制器示例中定义MainController($scope,$filter,$http) {
    • 现在 Send.php,使用 post 方法接收数据,从 angularjs $scope.SendEmail... $posdata 有一个编码 json,所以下一个 'json_decode' 你有一个包含 html 值的数组,你可以使用它$request-&gt;email ; $request-&gt;msg
    • 我不知道@marjes 是怎么回事。你的action.php 很好。只要您的模型值使用与您在$_POST['firstName'] 等中使用的相同的键,它们就会被检测到而不会出现问题。您也不需要设置headers: { 'Content-Type': 'application/x-www-form-urlencoded' },因为您的 PHP 应用程序将使用默认标头。
    猜你喜欢
    • 1970-01-01
    • 2020-02-24
    • 1970-01-01
    • 2023-04-10
    • 2016-03-07
    • 1970-01-01
    • 2013-11-25
    • 1970-01-01
    • 2018-11-17
    相关资源
    最近更新 更多