联系表单不会将数据从AngularJS传输到PHP

时间:2014-09-06 23:45:21

标签: php angularjs

我正在尝试从AngularJS文件中检索数据到PHP文件,但是我得到的错误是它是空的。 我找不到任何处理从angularJS发布数据到php文件的好例子,所以我需要帮助。

Angularjs文件:

angular.module('myApp', ['ajoslin.promise-tracker'])
.controller('help', function ($scope, $http, $log, promiseTracker, $timeout) {

$scope.ph_numbr =/[0-9]+/;


// Form submit handler.
$scope.submit = function(form) {
  // Trigger validation flag.
  $scope.submitted = true;

  // If form is invalid, return and let AngularJS show validation errors.
  if (!$scope.toggle || $scope.toggle.length <= 0 || form.$invalid) {
    return;
  }

  // Default values for the request.
  $scope.progress = promiseTracker('progress');
  var config = {
    params : {
      //'callback' : 'JSON_CALLBACK',
      'name' : $scope.name,
      'email' : $scope.email,
      'toggle' : $scope.toggle,
      'phone' : $scope.phone,
      'comments' : $scope.comments
    },
    tracker : 'progress'
  };


  $http({
                    method : 'POST',
                    url : 'js/contact.php',
                    data: config,
                    headers : {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}  

            })
    .success(function(data, status, headers, config) {
      if (data.success) {
        $scope.name = null;
        $scope.email = null;
        $scope.toggle = null;
        $scope.phone = null;
        $scope.comments = null;
        $scope.messages = 'Your form has been sent!';
        $scope.submitted = false;
      } else {
        $scope.messages = 'Oops, we received your request, but there was an error processing it.';
        $log.error(data);
      }
    })
    .error(function(data, status, headers, config) {
      $scope.progress = data;
      $scope.messages = 'There was a network error. Try again later.';
      $log.error(data);
    });

  // Hide the status message which was set above after 3 seconds.
  var promise = $timeout(function() { 
    $scope.messages = null; 
    }, 3000); 
    $scope.progress.addPromise(promise);
  };
});

php文件:

<?php
/*error_reporting(E_ALL);
ini_set('display_errors', '1');
require_once 'js/PHPMailerAutoload.php';*/

ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);

$data = file_get_contents("php://input");
$postData = json_decode($data);

if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['toggle']) && isset($_POST['comments'])) {

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

    $email = trim($_POST['email']);

    $subject = trim($_POST['toggle']);
    //email address settings
    $my_address = "*@yahoo.com";
    $headers = "From: ".$email;
    $message = "Name: " . $_POST['name'] . "\r\n\r\nMessage: " . $_POST["phone"] . "\r\n\r\nMessage: " . stripslashes($_POST['comments']);
    $to = $my_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;
    }

    mail($to, $subject, $message, $headers);
    $data = array('success' => true, 'message' => 'Thanks! We have received your message.');
    echo json_encode($data);


} else {

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

}

?>

我收到的错误消息是:“请完整填写表单” - 这意味着它没有获取值。

我的另一个问题是如何在AngularJS中从php文件中检索data.success值?

1 个答案:

答案 0 :(得分:1)

您似乎在这里获取数据:

$data = file_get_contents("php://input");
$postData = json_decode($data);

然后您使用$_POST代替。也许这会奏效:

if (empty($postData['name']) //etc

您似乎正在正确访问data.success,并且该值应设置为false,因为您的代码是当前的。

附加代码审查:

如果服务器上有错误,最好返回一个指示该状态的状态代码。同样,服务器返回200(默认),这意味着一切正常,即使请求实际上失败了。这将消除对data.success的需求。如果服务器发送状态200,则会激活您的.success功能。如果它返回错误状态,例如404,那么您的.error函数将会触发。

我怀疑你需要Content-Type标题。如果有必要,您可能需要重新考虑。

在Angular表单上,您应该将这些$scope属性嵌套在对象中:

$scope.formData = {
  name: '',
  email: '',
  //etc
}

然后,您只需将其直接传递到$http来电并重置您只需$scope.formData = {}的值即可。