Trigger javascript function depending on PHP condi

2019-07-31 03:31发布

I have a form that will return values in its URL, including whether the form is valid or not /contact2.php?result=contact-error-captcha&name=John /contact2.php?result=contact-ok&name=John

I am trying to trigger a Google Analytics Pageview depending on this value, which normally works in javascript like this: onclick="ga('send', 'pageview', '/mypage');"

Here is my last attempt, but it seems to not execute.

  <script type="text/javascript">
     function error-captcha() {
         alert("Hello! This works");
         ga('send', 'pageview', '/pages/contact-error-captcha');
     } 
     function contact-ok() {
         ga('send', 'pageview', '/pages/contact-ok');
     } 
     <?php if( $_GET['result'] == 'contact-error-captcha') : echo "error-captcha();"; endif; ?>
     <?php if( $_GET['result'] == 'contact-ok') :  echo "contact-ok();"; endif; ?>
 </script>

The problems I guess: - PHP should be before JS (but how?) - ga function should be "on" something (but how?)

I am not a pro coder, so any help appreciated.

1条回答
Evening l夕情丶
2楼-- · 2019-07-31 04:14

Issue in your function name not use '-' try this:

<script type="text/javascript">
     function error_captcha() {
         alert("Hello! This works");
         ga('send', 'pageview', '/pages/contact-error-captcha');
     } 
     function contact_ok() {
         ga('send', 'pageview', '/pages/contact-ok');
     } 
     <?php if( $_GET['result'] == 'contact-error-captcha') : echo "error_captcha();"; endif; ?>
     <?php if( $_GET['result'] == 'contact-ok') :  echo "contact_ok();"; endif; ?>
 </script>
查看更多
登录 后发表回答