繁体   English   中英

在HTTP请求发生之前在表单提交上调用JS函数

[英]Call JS function on form submit before http request occurs

我想在用户提交表单( POSTs )时将选定的复选框值传递给Google Analytics(分析),以作为Google Analytics(分析)仪表板中的自定义指标进行跟踪。

用户将选择的内容提交给服务器,服务器将首先调用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");
        }
    });
}

如果为表单提供id属性,则可以使用jQuery执行以下操作

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

或没有jQuery:

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

您可以在将提交事件发布到服务器之前对其进行拦截。 在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 } }); }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM