2015-06-02 26 views
0

当用户提交表单(POSTs)时,我希望将选定的复选框值传递给Google Analytics以作为Google Analytics仪表板中的自定义指标进行跟踪。在发出http请求之前调用表单提交的JS函数

用户将自己的选择提交给服务器,该服务器首先调用JS sendDataToGA(selectedOption) {函数将该数据传递给GA,然后POST将运行。

我该如何做到这一点?看起来POST正在触发而不是调用JS函数。

PHP/HTML:

<?php if (!empty($_POST)): ?> 
     Selection: <?php echo htmlspecialchars($_POST["option"]); ?><br> 

    <?php else: ?> 
     <!-- On form submit, fire a custom GA function to capture the selected option --> 
     <form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post" > 
      <input type="checkbox" name="option" value="option 1">Option 1<br> 
      <input type="checkbox" name="option" value="option 2">Option 2<br> 
      <input type="submit" value="Submit" id="submitBtn" onclick="sendDataToGA(selectedOption);"> 
     </form> 
    <?php endif; ?> 

JS:

function sendDataToGA(selectedCheckboxValue) { 
    ga('send', 'event', 'category', 'action', { 
     'metric1': selectedCheckboxValue, 
      'hitCallback': function() { 
      console.log("data has been sent to Google Analytics"); 
     } 
    }); 
} 

回答

1

如果你给你的表单的id属性,你可以用做以下jQuery

$("#myForm").submit(function() { 
    ga(...); 
}); 

或与out jQuery:

<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> onsubmit="sendDataToGA(selectedOption)" method="post"> 
    ... 
</form> 
+0

它说'sendDataToGA'功能没有被定义 – Growler

+0

您是否正确输入你的HTML JS文件?你能提供更多的代码吗? –

0

您可以在发送到服务器之前拦截提交事件。在jQuery中,这是您在domReady事件中附加的处理程序。这假定你的表单有id =“formid”,你可以通过设置everythingIsOkay = false来停止回发。

$(document).ready(function() { 
 
    $("#formid").submit(function(event) { //Catch form submit event 
 
     event.preventDefault(); //Stop it from posting back unless you tell it to 
 
     var everythingIsOkay = true; 
 
     
 
     //Do your processing here 
 
     
 
     if(everythingIsOkay){ 
 
      document.forms["formid"].submit(); //Go ahead and postback 
 
     } 
 
    }); 
 
});

+0

谢谢,但我没有在我的应用程序中使用jQuery – Growler

+0

足够简单,您应该可以使用具有相同功能的onsubmit标记:onsubmit =“function(event){...}” – Martin

相关问题