Trigger javascript function depending on PHP condition

谁说胖子不能爱 提交于 2019-12-11 08:14:01

问题


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:


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>


来源:https://stackoverflow.com/questions/42135231/trigger-javascript-function-depending-on-php-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!