Угловой контроллер не отображает сообщение

Я новичок в разработке на Angular / Bootstrap, и у меня есть контактная форма на моем сайте, которая использует контроллер Angular для вызова AJAX в файл PHP, который отправляет электронное письмо.

Пока все работает ~ вызов AJAX & отправив электронное письмо, оно должно отображать панель предупреждений на экране с текстом. По какой-то причине он отображает только панель «bg-danger» (в случае успеха он должен отображать панель bg-ssuccess) и никогда не отображает текстовое сообщение.

Вот изображение того, что происходит с контактной формой, после того как она успешно отправила сообщение
введите описание изображения здесь

Мой 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>

Мой угловой контроллер:

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';
};
//);

0

Решение

Измени его, чтобы он выглядел так

        $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) {

});
1

Другие решения

Других решений пока нет …

По вопросам рекламы [email protected]