角度控制器不显示消息

时间:2017-01-02 04:44:58

标签: php angularjs ajax angular-ui-bootstrap

我是Angular / Bootstrap的新手,我的网站上有一个联系表单,它使用Angular控制器对PHP文件进行AJAX调用,该文件发送电子邮件。

虽然一切正常但是AJAX呼叫&发送电子邮件时,它应该在屏幕上显示带有一些文本的警报栏。出于某种原因,它只显示“bg-danger”栏(成功时它应显示bg-ssuccess栏),它永远不会显示短信。

以下是联系表单成功发送邮件后所发生情况的图像 enter image description here

我的联系表单HTML:

<div class="container" ng-controller="ContactController">
  <div class="row">
    <div class="col-md-12">
              <div class="well well-sm">
                  <form class="form-horizontal" method="post" role="form" ng-submit="submit(contactform)" name="contactform">
                      <fieldset>
                          <legend class="text-center header">Send us a Message</legend>

                          <div class="form-group" ng-class="{ 'has-error': contactform.inputFirstName.$invalid && submitted }">
                              <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-user bigicon"></i></span>
                              <div class="col-md-8">
                                  <!--<input id="firstname" name="firstname" type="text" placeholder="First Name" required="required" class="form-control">-->
                                  <input ng-model="formData.inputFirstName" type="text" class="form-control" id="inputFirstName" name="inputFirstName" placeholder="First Name" required>
                              </div>
                          </div>
                          <div class="form-group" ng-class="{ 'has-error': contactform.inputLastName.$invalid && submitted }">
                              <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-user bigicon"></i></span>
                              <div class="col-md-8">
                                  <!--<input id="lastname" name="lastname" type="text" placeholder="Last Name" required="required" class="form-control">-->
                                  <input ng-model="formData.inputLastName" type="text" class="form-control" id="inputLastName" name="inputLastName" placeholder="Last Name" required>
                              </div>
                          </div>

                          <div class="form-group" ng-class="{ 'has-error': contactform.inputEmail.$invalid && submitted }">
                              <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-envelope-o bigicon"></i></span>
                              <div class="col-md-8">
                                  <!--<input id="emailid" name="emailid" type="text" placeholder="Email Address" required="required" class="form-control">-->
                                  <input ng-model="formData.inputEmail" type="email" class="form-control" id="inputEmail" name="inputEmail" placeholder="Email Address" required>
                              </div>
                          </div>

                          <div class="form-group" ng-class="{ 'has-error': contactform.inputPhone.$invalid && submitted }">
                              <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-phone-square bigicon"></i></span>
                              <div class="col-md-8">
                                  <!--<input id="phone" name="phone" type="text" placeholder="Phone" required="required" class="form-control">-->
                                  <input ng-model="formData.inputPhone" type="tel" class="form-control" id="inputPhone" name="inputPhone" placeholder="Phone" required>
                              </div>
                          </div>

                          <div class="form-group" ng-class="{ 'has-error': contactform.inputMessage.$invalid && submitted }">
                              <span class="col-md-1 col-md-offset-2 text-center"><i class="fa fa-pencil-square-o bigicon"></i></span>
                              <div class="col-md-8">
                                  <!--<textarea class="form-control" id="message" name="message" required="required" placeholder="Enter your massage for us here. We will get back to you within 2 business days." rows="7"></textarea>-->
                                  <textarea ng-Model="formData.inputMessage" class="form-control" id="inputMessage" name="inputMessage" placeholder="Enter your message for us here.  We will get back to you shortly..." rows="7" required></textarea>
                              </div>
                          </div>

                          <div class="form-group">
                              <div class="col-md-12 text-center">
                                  <button type="submit" class="btn btn-primary btn-lg" ng-disabled="submitButtonDisabled">Submit</button>
                              </div>
                          </div>
                      </fieldset>
                      <p ng-class="result" style="padding: 15px; margin: 0;">{{ resultMessage }}</p>
                  </form>
              </div>
          </div>
      </div>
  </div>

My Angular Controller:

var app = angular.module("myApp", ["ngRoute", "ngAnimate", "ngCsv"]);
app.config(function ($routeProvider) {
    $routeProvider.when("/", {
        templateUrl: "templates/home.html"
    }).when("/contact", {
        controller: 'ContactController',
        templateUrl: "templates/contact.html"
  })
});

app.controller('ContactController', function ($scope, $http) {
    $scope.result = 'hidden'
    $scope.resultMessage;
    $scope.formData; //formData is an object holding the name, email, subject, and message
    $scope.submitButtonDisabled = false;
    $scope.submitted = false; //used so that form errors are shown only after the form has been submitted
    $scope.submit = function(contactform) {
        $scope.submitted = true;
        $scope.submitButtonDisabled = true;
        if (contactform.$valid) {
            $http({
                method  : 'POST',
                url     : 'php/contact.php',
                data    : $.param($scope.formData),  //param method from jQuery
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  //set the headers so angular passing info as form data (not request payload)
            }).success(function(data){
                console.log(data);
                if (data.success) { //success comes from the return json object
                    $scope.submitButtonDisabled = false;
                    $scope.result='bg-success';
                    $scope.resultMessage = data.message;
                    //$scope.result='alert alert-success';
                } else {
                    $scope.submitButtonDisabled = true;
                    $scope.resultMessage = data.message;
                    $scope.result='bg-danger';
                }
            });
        } else {
            $scope.submitButtonDisabled = false;
            $scope.resultMessage = 'Failed <img src="http://www.chaosm.net/blog/wp-includes/images/smilies/icon_sad.gif" alt=":(" class="wp-smiley">  Please fill out all the fields.';
            $scope.result='bg-danger';
        }
    }
});

我在服务器端的PHP代码,用于发送电子邮件。

<?php
require_once ("class.phpmailer.php");   // Include phpmailer class
  ini_set('display_errors', 'On');
  error_reporting(E_ALL | E_STRICT);

  if (isset($_POST['inputFirstName']) && isset($_POST['inputLastName']) && isset($_POST['inputEmail']) && isset($_POST['inputPhone']) && isset($_POST['inputMessage'])) {

    //check if any of the inputs are empty
    if (empty($_POST['inputFirstName']) || empty($_POST['inputLastName']) || empty($_POST['inputEmail']) || empty($_POST['inputPhone']) || empty($_POST['inputMessage'])) {
        $data = array('success' => false, 'message' => 'Please fill out the form completely.');
        echo json_encode($data);
        exit;
    }

    $message=
    'First Name:    '.$_POST['inputFirstName'].'<br />
    Last Name:  '.$_POST['inputLastName'].'<br />
    Phone:  '.$_POST['inputPhone'].'<br />
    Email:  '.$_POST['inputEmail'].'<br />
    Comments:   '.$_POST['inputMessage'].'
    ';

    $mail = new PHPMailer();        // Instantiate the PHPMailer Class
    $mail->IsSMTP();                // enable SMTP
    $mail->SMTPDebug = 1;           // debugging: 1 = errors and messages, 2 = messages only
    $mail->SMTPAuth = true;         // SMTP authentication enabled
    $mail->SMTPSecure = 'ssl';      // secure transfer enabled + REQUIRED for Gmail (either SSL or TLS)
    $mail->Host = "smtp.gmail.com"; //Gmail SMTP Server to relay thru
    $mail->Port = 465; // Port 465 as we're using SSL... or use Port 587 for TLS
    $mail->IsHTML(true);                               // We're sending a HTML formatted message
    $mail->Username = "*****@gmail.com"; // Gmail account for authentication
    $mail->Password = "*********";                     // Gmail password for authentication
    $mail->SetFrom("*****@gmail.com");   // The email is being sent from this address
    $mail->Subject = "Website Contact Form Enquiry";   // The subject line of the email
    $mail->Body = ($message);                          // The actual email message to be sent
    $mail->AddAddress("*****@gmail.com"); // The email is being sent to this address

  //if (isset($_POST['ref'])) {
  //     $mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
  // }

   if(!$mail->send()) {
     $data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
     echo json_encode($data);
     exit;
   }

   $data = array('success' => true, 'message' => 'Thanks! We have received your message.');
   error_log("Data: ".$data['success']." Message: ".$data['message']);
   echo json_encode($data);
   //error_log("Data: ".$data['success']);

 } else {

     $data = array('success' => false, 'message' => 'Please fill out the form completely.');
     echo json_encode($data);

 }
?>

**更新 - 问题出在Angular端,我将控制器更改为此代码,但现在它总是成功的。另外,无论我尝试什么,当控制台日志显示它从PHP获取消息时,它从不显示消息:

if (contactform.$valid) {
            var request = $http({
                method  : 'POST',
                url     : 'php/contact.php',
                data    : $.param($scope.formData),  //param method from jQuery
                headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  //set the headers so angular passing info as form data (not request payload)
            });
            if (request.success) { //success comes from the return json object
                console.log(request);
                $scope.submitButtonDisabled = false;
                $scope.result='bg-success';
                $scope.resultMessage = "'Thanks!... We have received your message, and will be in contact shortly"
              } else {
                $scope.submitButtonDisabled = true;
                $scope.resultMessage = "Opps!... something went wrong.  Please Contact OpenHouse directly to let them know of this error.";
                $scope.result='bg-danger';
            };
            //);

1 个答案:

答案 0 :(得分:1)

将其更改为此胸罩

        $http({
            method  : 'POST',
            url     : 'php/contact.php',
            data    : $.param($scope.formData),  //param method from jQuery
            headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  //set the headers so angular passing info as form data (not request payload)
        }).success(function (response) {
          console.log(response); // object (not boolean)
        }).error(function (response) {

        });