【问题标题】:AngularJS + PHP Contact FormAngularJS + PHP 联系表
【发布时间】:2014-07-06 05:39:00
【问题描述】:

这个联系表格已经困扰我大约一周了,任何帮助都会很棒。

我已经设置好我的服务器和控制器,所以它会抓取我的 php 数据,并希望在提交表单时通过 php 处理数据。

控制器似乎正确地发布了数据,并且proccess.php 接收到了数据,我的 express、nginx 等日志确认这一切正常;数据似乎也可以发布;问题似乎出在我的 PHP 中。

我设置它来查询数据,并返回一个确认成功的 JSON 数组并随后邮寄数据;或报告失败;而且由于某种原因,它似乎每次都失败。

这是我的控制器:

mainControllers.controller('ContactCtrl', function ($scope, $http) {
$scope.formData;
$scope.processForm = function() {
console.log('Im in the controller');
console.log($scope.formData);
$http({
    method  : 'POST',
    url     : '/process.php',
    data    : $.param($scope.formData), 
    headers : { 'Content-Type': 'application/x-www-form-urlencoded' } 
}).success(function(formData) {
        console.log(formData);
        if (formData.success) {
            console.log('Success');
        } else {

            console.log('Fail');
        }
    });
};
});

我的php:

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

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

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

    //create an instance of PHPMailer
    $mail = new PHPMailer();

    $mail->From = $_POST['inputEmail'];
    $mail->FromName = $_POST['inputName'];
    $mail->AddAddress('something@test.com'); //recipient
    $mail->Subject = $_POST['inputName'];
    $mail->Body = "Phone: " . $_POST['inputPhone'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);

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

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

    $formData = array('success' => true, 'message' => 'Thanks! We have received your message.');
    echo json_encode($formData);

} else {

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

}

和html:

<form id="myform" name="myForm" data-abide role="form" ng-submit="processForm()">
  <div class="formData.inputName-field">
    <label>Your name <small>required</small>
      <input type="text" name="formData.inputName" id="formData.inputName" required pattern="[a-zA-Z]+" ng-model="formData.inputName">
    </label>
    <small class="error">Name is required.</small>
  </div>
  <div class="formData.inputEmail-field">
    <label>Email <small>required</small>
      <input type="email" name="formData.inputEmail" id="formData.inputEmail" required ng-model="formData.inputEmail">
    </label>
    <small class="error">An email address is required.</small>
  </div>

  <div class="formData.inputPhone-field">
    <label>Phone #
    <input type="text" name="formData.inputPhone" id="formData.inputPhone"required pattern="^([0-9]( |-)?)?(\(?[0-9]{3}\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[a-zA-Z0-9]{7})$" ng-model="formData.inputPhone">
    </label>
    <small class="error">Please enter your number in the format '123-456-7890'.</small>
    </div>
    <div class="formData.inputMessage-field">
    <label>Message
    <textarea name="formData.inputMessage" id="formData.inputMessage" ng-model="formData.inputMessage"></textarea> </label></div>
  <button type="submit" class="columns small-centered">Submit</button>
  <div class="panel">
<p>{{formData}}</p>
<p>{{codeStatus}}</p>
</div>
</form>

【问题讨论】:

  • 它到底在哪里失败了?响应是什么样的?
  • 我添加了一些日志来尝试查明问题,一个在if (formData.success) { console.log('Success'); } else { // if successful, bind success message to message console.log('Fail'); } 的控制器中调用,另一个在else { $formData = array('success' =&gt; false, 'message' =&gt; 'Please fill out thsdffe form completely.'); echo json_encode($formData); } 的php 文件中
  • 所以在 .success(function(formData) 块以及 php 的第二个 $formData = 块中......另外,我尝试修改 php 以取消验证并看到'空字符串'(我相信那是消息'..这是来自控制台的屏幕,分别显示响应和 POST 选项卡;gyazo.com/6046ac608bd42ef4b8797950cf69f1e6gyazo.com/5188e4b02a2aba85b14193b23e062b9f 似乎数据已正确发布,但似乎 PHP 没有解释formData 符合预期。
  • 尝试var_dump($_POST)。它看起来像什么?
  • 将我的 php 文件更改为 &lt;?php var_dump($_POST); 产生 array(0) { }

标签: php forms angularjs


【解决方案1】:

正如你所说,它似乎工作正常,但由于某种原因,每次都会调用失败函数。

如果你查看你的代码,你会调用 $http.success 函数,在里面你可以再次检查是否成功。

由于您最有可能检查 $http 响应的正确返回,因此您应该直接在 $http 上使用 .success 和 .error 函数,而不是在 $http.success 内。看看这个:

$http({method: 'GET', url: '/someUrl'}).
  success(function(data, status, headers, config) {
  // this callback will be called asynchronously
  // when the response is available
}).
  error(function(data, status, headers, config) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
});

所以尝试将你的失败代码从 .success 函数中移到 .error 函数中,看看结果如何。

更多阅读:查看https://docs.angularjs.org/api/ng/service/$http

【讨论】:

  • 由于他们总是从服务器返回status 200,这无助于解决问题。捕获错误是个好主意(例如,当服务器可能关闭或网络连接丢失时),但这与问题中的问题无关。
  • 我明白了,抱歉,我好像误会了
  • 感谢@ChrisPreston 的输入通常遵循该格式可能是一个好主意,但不幸的是问题似乎出在 PHP 中,至少目前所有迹象都指向这一点
【解决方案2】:

擦除周围的 if else 语句。还有一个问题:没有加载phpMailer类。

【讨论】:

    【解决方案3】:

    对于仍然感兴趣的人,我必须配置 express 以使用 php-express 正确处理 PHP,如下所示:

    var phpExpress = require('php-express')({
        binPath: '/usr/bin/php' // php bin path.
    });
    
    module.exports = function(app) {
      app.engine('php', phpExpress.engine);
      app.set('view engine', 'php');
      app.all(/.+\.php$/, phpExpress.router);
    };
    

    然后在我的控制器中,我能够通过以下方式传递表单数据:

    '使用严格';

    angular.module('contactApp')
      .controller('ContactCtrl', function ($scope, $http, $state) {
        $scope.formData;
        $scope.processForm = function() {
        $http({
            method  : 'POST',
            url     : '/process.php',
            data    : $.param($scope.formData),  // 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)
        }).success(function(formData) {
                console.log(formData);
                $state.go('success');
            }).error(function(formData){
                if (formData.success) {
                    console.log('Success');
                } else {
                    console.log('Fail');
                    $state.go('contact_err');
                }
            });
        };
        });
    

    还有一个 process.php,看起来像:

    <?php
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    require_once 'phpmailer/PHPMailerAutoload.php';
    
    if (isset($_POST['inputName']) && isset($_POST['inputEmail']) && isset($_POST['inputPhone']) && isset($_POST['inputMesage'])) {
    
        //check if any of the inputs are empty
        if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputPhone']) || empty($_POST['inputMesage'])) {
            $formData = array('success' => false, 'message' => 'Please fill out the form completely.');
            echo json_encode($formData);
            exit;
        }
    
        //create an instance of PHPMailer
        $mail = new PHPMailer();
        $mail->isSMTP();
    
        //Enable SMTP debugging
        // 0 = off (for production use)
        // 1 = client messages
        // 2 = client and server messages
        $mail->SMTPDebug = 0;
    
        //Ask for HTML-friendly debug output
        $mail->Debugoutput = 'html';
    
        //Set the hostname of the mail server
        $mail->Host = 'email.host.com';
    
        //Set the SMTP port number - 587 for authenticated TLS, a.k.a. RFC4409 SMTP submission
        $mail->Port = 587;
    
        //Set the encryption system to use - ssl (deprecated) or tls
        $mail->SMTPSecure = 'tls';
    
        //Whether to use SMTP authentication
        $mail->SMTPAuth = true;
    
        //Username to use for SMTP authentication - use full email address for gmail
        $mail->Username = "email@sender.com";
    
        //Password to use for SMTP authentication
        $mail->Password = "passwordredacted";
        $mail->setFrom = $_POST['inputEmail'];
        $mail->addAddress('example@recipient.com'); //recipient
        $mail->Subject = $_POST['inputName'];
        $mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMesage']) . "\r\n\r\nPhone: " . stripslashes($_POST['inputPhone']) . "\r\n\r\nEmail: " . stripslashes($_POST['inputEmail']);
    
        if (isset($_POST['ref'])) {
            $mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
        }
    
        if(!$mail->send()) {
            $formData = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
            echo json_encode($formData);
            exit;
        }
    
        $formData = array('success' => true, 'message' => 'Thanks! We have received your message.');
        echo json_encode($formData);
    
    } else {
        var_dump($_POST);
        $formData = array('success' => false, 'message' => 'Please fill out the form completely.');
        echo json_encode($formData);
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-28
      • 2010-09-17
      • 2013-03-14
      • 2012-04-20
      相关资源
      最近更新 更多