简体   繁体   中英

JavaScript: Analytics Track Event won't fire

I've put the function into form validation part, so that only when form is valid, the beacon would be sent. I am sure I am missing something. See code below.

function checkForm() {
    var error = "";
    if($("#first_name").val()=="") { error+="- Enter your first name.\n";};
    if(error=="") {
        _gaq.push(['_trackEvent','Form','Submit','Newsletter']);
        return true;
    } else {
        alert("Please correct these form errors before you submit the form:\n\n"+error)
        return false;
    }
}

EDIT : Thanks everyone for their help! Tested this one, and 100ms doesn't seem to be enough.

Now I am thinking to do this a little more clever way. It would make sense to submit it, once all required fields have text in it, but it should be clever enough to submit more than once and submit only when data is valid!

Are you sure if it's not fires? Probably there is some delay in analytics data refresh. If you develop your app on localhost, then you should set _setDomainName property to 'none'

_gaq.push(['_setAccount', 'Your-account-id']);
_gaq.push(['_setDomainName', 'none']);

@see: GA Event Tracking from localhost

Try to give a delay (may be about 100 miliseconds or less) using setTimeout() or setInterval() and let the GA datato be submited. Worked for me.

function gaSubmit(param){
_gaq.push(param);
}

function checkForm() {
    var error = "";
    if($("#first_name").val()=="") { error+="- Enter your first name.\n";};
    if(error=="") {
        setTimeout(gaSubmit(['_trackEvent','Form','Submit','Newsletter']),100);
        return true;
    } else {
        alert("Please correct these form errors before you submit the form:\n\n"+error)
        return false;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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