2016-11-03 26 views
0

我想通過調用AJAX函數將Angular $ scope值傳遞給Hubspot表單。

我在控制器中進行計算,然後我希望將這些數據輸入到相應的Hubspot表單字段。

在我的角度控制器我有這樣的:

$scope.submit = function(valid) { 
    $scope.$watch(function() { 
     return $scope.selectedValue 
    }, function() { 
     $scope.calculation = $scope.input1 * $scope.selectedValue; 
    } 
    } 

我想在$ scope.calculation值傳遞給PHP腳本,然後hubspot形式。

我的代碼如下所示:

$.ajax({ 
       url: 'form.php', 
       type: 'POST', 
       dataType: "json", 
       data: { 
        company: $('#company').val(), 
        firstname: $('#firstname').val(), 
        lastname: $('#lastname').val(), 
        jobtitle: $('#jobtitle').val(), 
        email: $('#email').val(), 
        calculation: $scope.calculation 
       } 

,我只是用Hubspot PHP API這個部分特別收集的輸入數據。

$str_post = "company=" . $_POST["company"] 
. "&firstname=" . $_POST["firstname"] 
. "&lastname=" . $_POST["lastname"] 
. "&jobtitle=" . $_POST["jobtitle"] 
. "&email=" . $_POST["email"] 
. "&calculation=" . $_POST["calculation"] 
. "&hs_context=" . urlencode($hs_context_json); //Leave this one be 

我試着相應$範圍設置爲一個變量名,仍然一無所獲。

任何幫助將非常感激。謝謝。

+1

天啊 - 使用角度的內置'$ http'模塊 - 並使用實際的'$'scope'值ngModel' * * not ** jquery'.val()'方法 - 可能導致問題的至少一部分*。 – tymeJV

+0

10 4,會相應更新 – FraserKC

回答

0

只是爲了建立在其他答案中的內容,您會發現使用Angular的$http服務更容易。 AJAX調用需要在您的控制器內完成。

執行此類表單提交的最佳方式是使用ng-model指令將input元素鏈接到$scope。然後,在表單提交後,您可以使用ng-submit指令在控制器中調用submit函數。聽起來很複雜,但作品很有魅力。

HTML

<div ng-controller="YourController"> 
    <form ng-submit="submit(myForm.$valid)" name="myForm" novalidate> 
     <input ng-model="responses.company" type="text"> 
     <!-- More fields go here, all linked to scope with ng-model --> 
    </form> 
</div> 

JS

app.controller('YourController', ['$scope', '$http', function($scope, $http){ 
    $scope.responses = {};   

    $scope.submit = function(valid){ 
     if(valid){ 

      var calculation = parseFloat($scope.responses.input1) * parseFloat($scope.responses.selectedValue); 

      $http({ 
       method: 'POST', 
       url: 'form.php', 
       data: { 
        company: $scope.responses.company, 
        firstname: $scope.responses.firstname, 
        lastname: $scope.responses.lastname, 
        jobtitle: $scope.responses.jobtitle, 
        email: $scope.responses.email, 
        calculation: calculation 
       } 
      }).then(function successCallback(response) { 
       //Success! 
      }, function errorCallback(response) { 
       //Failure :(
      }); 
     } 
    }; 
}]);