1

I have a PHP file that is used to send emails, while my Angular controller sends the data to be sent in the emails. I am trying to do error handling on my Angular callBacks in the events when the emails are sent and are not sent:

Angular controllor:

$scope.processForm = function() {
  $scope.httpCallText = "Sending...";
  $scope.httpCall = {
    'background-color' : '#663300'
  };

  $http({
    method  : 'POST',
    url     : '/php/contact.php',
    data    : $.param($scope.contactData),  // pass in data as strings
    headers : { 'Content-Type': 'application/x-www-form-urlencoded' }  // set the headers so angular passing info as form data (not request payload)
  }).then(function successCallback(data) {
    console.log(data);
    if(!data['success']) {
      $scope.httpCallText = "Error. Please Try Again.";
      $scope.httpCall = {
        'background-color' : 'red'
      };
    }
    else {
      $scope.httpCallText = "Sent! Thank You for Your Message"
      $scope.httpCall = {
        'background-color' : 'green'
      }
    }

  }, function errorCallback(response) {
    $scope.httpCallText = "Error. Please Try Again.";
    $scope.httpCall = {
      'background-color' : 'red'
    };
  });
};

My PHP:

<?php
require_once "../vendors/PHPMailer-master/PHPMailerAutoload.php";

print_r($_POST);
$data = array();

$sender_name = isset($_POST['sender_name']) ? $_POST['sender_name'] : '';
$sender_email = isset($_POST['sender_email']) ? $_POST['sender_email'] : '';
$sender_tel = isset($_POST['sender_tel']) ? $_POST['sender_tel'] : '';
$sender_message = isset($_POST['sender_message']) ? $_POST['sender_message'] : '';

$mail = new PHPMailer;

//Enable SMTP debugging. 
$mail->SMTPDebug = 3;                               
//Set PHPMailer to use SMTP.
$mail->isSMTP();            
//Set SMTP host name                          
$mail->Host = "smtp.gmail.com";
//Set this to true if SMTP host requires authentication to send email
$mail->SMTPAuth = true;                          
//Provide username and password     
$mail->Username = "*****@gmail.com";                 
$mail->Password = "******";                           
//If SMTP requires TLS encryption then set it
$mail->SMTPSecure = "tls";                           
//Set TCP port to connect to 
$mail->Port = 587;                                   

$mail->From = $sender_email;
$mail->FromName = $sender_name;


$mail->addAddress("blah@blah.com", "Blah");

$mail->isHTML(true);

$mail->Subject = "Message Sent from jcrageralternatives.com by: ".$sender_name;
$mail->Body = "<p>Name: ".$sender_name."</p><p>Email Provided: ".$sender_email."</p><p>Phone Number Provided: ".$sender_tel."</p><p>Message: '".$sender_message."'</p>";
$mail->AltBody = $sender_message;

if(!$mail->send()) 
{
    print_r("Mailer Error: " . $mail->ErrorInfo);
    $data['success'] = false;
} 
else 
{
    print_r("Message has been sent successfully");
    $data['success'] = true;
}

echo json_encode($data);
?>

In my successCallback in my controller, if I do if(!data.success), I always get a red button (data.success evaluates to false) regardless of whether or not the email was sent. However, if I do if(data.success==false), I always get a green button, regardless of whether or not the email was sent. How can I get the statements to evaluate to what they're supposed to evaluate to? Thank you!

EDIT: When I console.log response.data I see the {"success" :false}, but when I console.log response.data['success'] I get undefined. This is what I get in my console for response.data :

2016-01-16 02:34:28 Connection: opening to smtp.gmail.com:587, timeout=300, options=array (
                                  )
2016-01-16 02:34:28 Connection: opened
2016-01-16 02:34:29 SERVER -> CLIENT: 220 smtp.gmail.com ESMTP ry1sm18220246pab.30 - gsmtp
2016-01-16 02:34:29 CLIENT -> SERVER: EHLO localhost
2016-01-16 02:34:29 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [73.15.255.61]
                                  250-SIZE 35882577
                                  250-8BITMIME
                                  250-STARTTLS
                                  250-ENHANCEDSTATUSCODES
                                  250-PIPELINING
                                  250-CHUNKING
                                  250 SMTPUTF8
2016-01-16 02:34:29 CLIENT -> SERVER: STARTTLS
2016-01-16 02:34:29 SERVER -> CLIENT: 220 2.0.0 Ready to start TLS
2016-01-16 02:34:29 CLIENT -> SERVER: EHLO localhost
2016-01-16 02:34:29 SERVER -> CLIENT: 250-smtp.gmail.com at your service, [73.15.255.61]
                                  250-SIZE 35882577
                                  250-8BITMIME
                                  250-AUTH LOGIN PLAIN XOAUTH2 PLAIN-CLIENTTOKEN OAUTHBEARER XOAUTH
                                  250-ENHANCEDSTATUSCODES
                                  250-PIPELINING
                                  250-CHUNKING
                                  250 SMTPUTF8
2016-01-16 02:34:29 CLIENT -> SERVER: AUTH LOGIN
2016-01-16 02:34:29 SERVER -> CLIENT: 334 VXNlcm5hbWU6
2016-01-16 02:34:29 CLIENT -> SERVER: dmliaHUxMjAxQGdtYWlsLmNvbQ==
2016-01-16 02:34:29 SERVER -> CLIENT: 334 UGFzc3dvcmQ6
2016-01-16 02:34:29 CLIENT -> SERVER: Q0BycGVEMWVt
2016-01-16 02:34:29 SERVER -> CLIENT: 235 2.7.0 Accepted
2016-01-16 02:34:29 CLIENT -> SERVER: MAIL FROM:<v@v>
2016-01-16 02:34:29 SERVER -> CLIENT: 250 2.1.0 OK ry1sm18220246pab.30 - gsmtp
2016-01-16 02:34:29 CLIENT -> SERVER: RCPT TO:<****@gmail.com>
2016-01-16 02:34:29 SERVER -> CLIENT: 250 2.1.5 OK ry1sm18220246pab.30 - gsmtp
2016-01-16 02:34:29 CLIENT -> SERVER: DATA
2016-01-16 02:34:29 SERVER -> CLIENT: 354  Go ahead ry1sm18220246pab.30 - gsmtp
2016-01-16 02:34:29 CLIENT -> SERVER: Date: Sat, 16 Jan 2016 02:34:28 +0000
2016-01-16 02:34:29 CLIENT -> SERVER: To: **** **** <****@gmail.com>
2016-01-16 02:34:29 CLIENT -> SERVER: From: v <v@v>
2016-01-16 02:34:29 CLIENT -> SERVER: Subject: Message Sent from jcrageralternatives.com by: v
2016-01-16 02:34:29 CLIENT -> SERVER: Message-ID: <421aa50e45d9e33b9b7c41918d99af59@localhost>
2016-01-16 02:34:29 CLIENT -> SERVER: X-Mailer: PHPMailer 5.2.14 (https://github.com/PHPMailer/PHPMailer)
2016-01-16 02:34:29 CLIENT -> SERVER: MIME-Version: 1.0
2016-01-16 02:34:29 CLIENT -> SERVER: Content-Type: multipart/alternative;
2016-01-16 02:34:29 CLIENT -> SERVER:   boundary="b1_421aa50e45d9e33b9b7c41918d99af59"
2016-01-16 02:34:29 CLIENT -> SERVER: Content-Transfer-Encoding: 8bit
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER: This is a multi-part message in MIME format.
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER: --b1_421aa50e45d9e33b9b7c41918d99af59
2016-01-16 02:34:29 CLIENT -> SERVER: Content-Type: text/plain; charset=us-ascii
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER: as;lkdfjas;ldkf
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER: --b1_421aa50e45d9e33b9b7c41918d99af59
2016-01-16 02:34:29 CLIENT -> SERVER: Content-Type: text/html; charset=us-ascii
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER: <p>Name: v</p><p>Email Provided: v@v</p><p>Phone Number Provided: 1234567891</p><p>Message: 'as;lkdfjas;ldkf'</p>
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER: --b1_421aa50e45d9e33b9b7c41918d99af59--
2016-01-16 02:34:29 CLIENT -> SERVER:
2016-01-16 02:34:29 CLIENT -> SERVER: .
2016-01-16 02:34:30 SERVER -> CLIENT: 250 2.0.0 OK 1452911670 ry1sm18220246pab.30 - gsmtp
2016-01-16 02:34:30 CLIENT -> SERVER: QUIT
2016-01-16 02:34:30 SERVER -> CLIENT: 221 2.0.0 closing connection ry1sm18220246pab.30 - gsmtp
2016-01-16 02:34:30 Connection: closed
{"success":true}
vibhu1201
  • 143
  • 8

4 Answers4

0

The format of .then is

.then(function(success){},function(error){})

so If it triggers on first block that's mean it's successfully done.

If it triggers on 2nd block that;s mean it's has error.

so you don't need to check in success that response is success or not.

Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
0

From your PHP code, there is no change to HTTP status, so I assume that your response is always status 200. If that's the case, errorCallback of $http will never be called because it considers non-2xx status as error.

The next issue is the signature of successCallback. successCallback is called with response object for $http. So the actual JSON that you are interested with should be accessed with response.data. So it should look like this:

$http(myHttpConfig).then(function(response) { // `response` here!
  console.log(response.data); // { success: true }, data from PHP
});

For the difference of !data.success and data.success == false, look at the following:

$http(myHttpConfig).then(function(data) { // `data` here is `response`!
  console.log(data.success); // undefined

  // `response` does not have `success` property so it is undefined, so...
  // !data.success => !undefined => true
  // data.success == false => undefined == false => false
});
PSWai
  • 1,198
  • 13
  • 32
  • If response.data doesn't have a success property even though I'm sending a success property through my php, how would I access it in my success/error functions in my controller? – vibhu1201 Jan 15 '16 at 20:34
  • When I `console.log(response.data)`, I see `{"success":false}`, but when I `console.log(response.data['success'])`, I get `undefined`. Why is that? – vibhu1201 Jan 15 '16 at 20:48
  • @user3810313 it sounds like `response. data` is a string instead of object. Try to set `Content-type` to `application/json` in your PHP. – PSWai Jan 16 '16 at 00:21
  • By right Angular should be able to detect json and parse it automatically. Meanwhile you can try to parse yourself using `angular. fromJson`. I will update this answer later – PSWai Jan 16 '16 at 00:24
  • I tried setting the header right before I `echo json_encode($data)` but I get a Warning that says that I can't modify header information because the headers are already sent by PHPMailer (the mail client I'm using to send the emails). – vibhu1201 Jan 16 '16 at 01:04
  • Finally got to my pc. That's because of the `print_r($_POST)` in your PHP script. In PHP, header can only be set before any output is written. Look at [this for more info](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php). – PSWai Jan 16 '16 at 03:32
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/100825/discussion-between-pswai-and-vibhu1201). – PSWai Jan 16 '16 at 06:44
0

On php side try to set response status manually

http_response_code(200); // request was successful
http_response_code(500); // error

On angulars side

$http.post(url, data).success(function(data) {}).error(function(data) {});
Mike Kor
  • 876
  • 5
  • 14
0

Try this,

$http({
              method  : 'POST',
              url     : '/php/contact.php',
              data    : $.param($scope.contactData),
      }).then(function successCallback(response) {
          console.log(response);  
      }, function errorCallback(response) {
          console.log(response);
      });
krishnakumar
  • 118
  • 1
  • 1
  • 11