2017-01-03 20 views
0

これは以前の質問を繰り返しても申し訳ありませんが、私の問題で動作するように思われる解決策を見つけられませんでした&

私は電子メールを送信するためにPHPとデータをやりとりするAngularフォームを持っています。問題はPHPからのJSON応答を処理することです(PHPはJSON自体の中で成功したかどうかをメッセージとともに伝えます)。 JSON内に含まれる「成功」値に基づいてコードを応答することはできません。実際には「メッセージ」も表示されません。

JSON応答データは次のようになります問題): enter image description here

だから私の角度コードもJSONでAJAXによって渡される「メッセージ」を表示しながら、真または偽が「成功」に基づいて応答する必要がある

マイ角度コントローラー・コード。:

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; 
    $scope.submit = function(contactform) { 
     $scope.submitted = true; 
     $scope.submitButtonDisabled = true; 
     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' } 
      }); 
      if (request.success) { 
       console.log(request); 
       $scope.submitButtonDisabled = false; 
       $scope.result='bg-success'; 
       $scope.resultMessage = request.message; 
       } else { 
       $scope.submitButtonDisabled = true; 
       $scope.resultMessage = request.message; 
       //$scope.resultMessage = "Opps!... something went wrong. Please Contact OpenHouse directly to let them know of this error."; 
       $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 = "[email protected]"; // Gmail account for authentication 
    $mail->Password = "*********";      // Gmail password for authentication 
    $mail->SetFrom("[email protected]"); // 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("[email protected]"); // The email is being sent to this address 

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

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

    } else { 
     echo json_encode(['success' => false, 'message' => 'Please fill out the form completely.']); 
    } 
?> 
+1

読む:

はここで働いて角度コントローラです。 $ httpはレスポンスボディを返さず、レスポンスオブジェクトを含む約束を返します。ヘッダやステータスなどのレスポンスボディを含みます。 –

+0

また、PHPからオブジェクトへのレスポンスを自動的に解析する角度JSONの文字列であれば、 '$ http'が非同期で、' request'変数がプロミスを返すので、あなたのレスポンスで 'content-type:application/json'ヘッダーを返すべきです、 –

+1

@BlissSolはRon Dadonの答えで拡張します'' if(request.success) ''あなたが '' request.then(function(response){if(response.data.success){...}} ')をしたいと思うでしょう。 ' – Fissio

答えて

3

起動するには、$ HTTPはrequestオブジェクトを返しません、それはresponseオブジェクトに解決の約束を返します。

 //var request = $http({ 
     //It returns a promise 
     var promise = $http({ 
      method : 'POST', 
      url  : 'php/contact.php', 
      data : $.param($scope.formData), //param method from jQuery 
      headers : { 'Content-Type': 'application/x-www-form-urlencoded' } 
     }); 
     //Use .then method to receive response 
     promise.then(function (response) { 
      var request = response.data; 
      if (request.success) { 
      console.log(request); 
      $scope.submitButtonDisabled = false; 
      $scope.result='bg-success'; 
      $scope.resultMessage = request.message; 
      } 
     }); 

あることを認識することが重要です$ httpサービスはを保留にして、すぐにを返します。応答がサーバーから戻ってくると、約束は(解決済または拒否のいずれか)です。

約束の.thenメソッドを使用して、成立または拒否応答で解決する成功および拒否ハンドラを提供します。

は、詳細については、以下を参照してください。AngularJS $http Service API Reference - General Usage


UPDATE

Content-Type: 'application/json'を使用して、デフォルトの符号化とポストによってAngularJSフレームワーク。そして、AngularJSとPOSTを簡略化することができる

$json = file_get_contents('php://input'); 
$obj = json_decode($json); 

は、PHPのバックエンドでJSONデータを受信するには、ような何かの助けを

var promise = $http({ 
     method : 'POST', 
     url  : 'php/contact.php', 
     //data : $.param($scope.formData), //param method from jQuery 
     data: $scope.data; 
     //headers : { 'Content-Type': 'application/x-www-form-urlencoded' } 
     //Defaults to: 
     //headers: {'Content-Type': 'application/json'} 
    }); 
    //Use .then method to receive response 
    promise.then(function (response) { 
     var request = response.data; 
     if (request.success) { 
     console.log(request); 
     $scope.submitButtonDisabled = false; 
     $scope.result='bg-success'; 
     $scope.resultMessage = request.message; 
     } 
    }); 
+0

私はすべての変更を全員に行った推薦しましたが、私はまだ変数 "request.message"の "undefined"を取得しますか? さらに、@georgawgの変更を加えれば、 'request'はもともと私が投稿したのとまったく同じJSONデータを返しています(したがって、「成功」または「メッセージ」の値にアクセスできません。 JSON。 – BlissSol

+0

"成功"と "メッセージ"の値がJSONとしてパッケージ化されて返される前に配列内(PHP側)にパッケージ化されていますか? – BlissSol

+0

[小さなプログラムをデバッグする方法] /ericlippert.com/2014/03/05/how-to-debug-small-programs/)。 – georgeawg

0

みんなありがとうを。 asyn httpコール&が画面に表示された後で応答を返すことができました... 何を試しても、データ応答内のデータで常にHTTPヘッダーがパッケージ化されます。

PHPが電子メールを送信しなかった場合(電子メールを送信するためのコマンドをすべて削除した場合)、データ応答は単なるデータになります。 PHPが電子メールを送信した場合、応答はHTTPヘッダー+データ応答内のデータになります。

最後にAngular側でデータのレスポンスを文字列に変換し、その文字列を{に分割して、データ(ヘッダーなし)だけを新しい文字列にします。\文字列内の値、そして明らかにそして終わり}

したがって、私は望む応答を得ることができました。 [$ HTTP](https://docs.angularjs.org/api/ng/service/$http)サービスについての

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; 
    $scope.submit = function(contactform) { 
     $scope.submitted = true; 
     $scope.submitButtonDisabled = true; 
      var promise = $http({ 
       method : 'POST', 
       url  : 'php/contact.php', 
       data : { 
        firstname: $scope.formData.inputFirstName, 
        lastname: $scope.formData.inputLastName, 
        emailid: $scope.formData.inputEmail, 
        phoneno: $scope.formData.inputPhone, 
        message: $scope.formData.inputMessage 
       }, 
       headers : {'Content-Type': 'application/json'} 
      }) 
      promise.then(function (response) { 
       var request = JSON.stringify(response.data); //convert JSON data to string for manipulation 
       var startpos = request.indexOf("{");   //locate '{' as its the start of the data we want 
       var endpos = request.lastIndexOf("}");  //locate '}' as its the end of the data we want 
       var res = request.slice(startpos, endpos); //Extract the actual data now we know where it is. 
       var newresponse = res.split("\\");   //Split the data into new array 
       var answer = request.search("true");   //search the string to see if it contains the word "true" meaning an email was sent. 

       if (answer >= 0) { 
       $scope.submitButtonDisabled = false; 
       $scope.result='bg-success'; 
       $scope.resultMessage = newresponse[5].replace('"', " "); 
       } else { 
       $scope.submitButtonDisabled = true; 
       $scope.resultMessage = newresponse[5].replace('"', " "); 
       $scope.result='bg-danger'; 
       } 
      }); 
     } 
    });