JavaScript: Analytics Track Event won't fire - javascript

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!

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;
}
}

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

Related

How do I ask the user to confirm they want to leave the page?

I have a web site that contains several pages where the user can add and edit information. In order to provide a consistent UI, I have the following JavaScript function...
function setWindowBeforeUnload(changed) {
$(window).on("beforeunload", function() {
if (confirmLeave && changed && changed()) {
return "You haven't saved the information. If you leave this page, the information will be lost.";
}
});
}
confirmLeave is a global variable that specifies if we are to ask them for confirmation before navigating away (which we don't if we are navigating to another page after a successful save). changed is a function that checks if the entity has changed.
This is called from a details page (say the customer page) as follows...
$(document).ready(function() {
setWindowBeforeUnload(customerChanged);
});
function customerChanged() {
// Checks the data and returns true or false as appropriate
}
This all worked fine until recently, when a change in Chrome broke it.
I have searched for hours, and found loads of people suggesting code like this...
addEventListener('beforeunload', function(event) {
event.returnValue = 'You have unsaved changes.';
});
...which works fine as it is, except that it fires the warning whenever they leave the page, irrespective of whether or not the data has changed.
As soon as I try to add any logic (such as my checking code in the first sample), it doesn't work...
function setWindowBeforeUnload(changed) {
addEventListener('beforeunload', function(event) {
if (confirmLeave && changed && changed()) {
event.returnValue = 'You have unsaved changes.';
}
});
}
With this code, I can navigate away from the page without getting a warning.
Is there any way to reproduce my original behaviour now?
You can use logic in the handler, you just can't have a custom message any more.
See the code below. Use the "Run code snippet" to simulate navigation. Run the snippet, run it again no confirm. Toggle the button to "false" run the snippet and get a confirm.
var test = true;
function otherTest() {
return true;
}
addEventListener('beforeunload', function(event) {
if(!test || !otherTest()) {
event.returnValue = 'You have unsaved changes.';
}
});
document.getElementById('theButton').addEventListener('click', function(event) {
test = !test;
this.innerHTML = test.toString();
});
<p>Click the button to turn the confirm on and off</p>
<button id="theButton">true</button>

Javascript Alert when click close button

I have the following code, When I click on close (X) button it shows error stored in variable s. Before the script was working good but now its not showing alert when i click on close button. Did i do any mistake in coding or I need to add some .js file for this to work.
var internalLink = false;
function pageUnload() {
if (!internalLink && location.protocol != 'http:') {
internalLink = true;
var s = 'Alert Message';
if (navigator.userAgent.indexOf("Firefox") > -1) {
alert(s);
}
setTimeout("location.href= 'foo.com'", 100);
return s;
}
}
window.onbeforeunload = pageUnload;
Or Can you provide me some other code so that when user clicks on close button. Browser will show alert stored in variable s. Note: Only show alert when click close, Not then when redirects to other link or when submit the form. it should not show any alert when click internal links.
There is very little that browsers will allow the onbeforeunload to do. Heck, not all of them even support it. I'm pretty sure Opera doesn't.
What this event is meant for is to show a confirmation box asking if you want to leave or not. That's it. You can't call alert or confirm, redirect the user, make an (asynchronous) AJAX call, or do a whole lot else.
What you can do is return a string. That returned string will be shown on a browser-rendered alert asking if you want to leave or not. Note: Firefox won't actually display your string (see bug# 588292).
var internalLink = false;
function pageUnload() {
if (!internalLink && location.protocol != 'http:') {
internalLink = true;
var s = 'Alert Message';
// You cannot alert or set location.href here
// This will show your message in a confirm popup
return s;
}
}
window.onbeforeunload = pageUnload;
So, as you can see browsers are very picky about how they handle or even trigger onbeforeunload. Use it with caution.
There is no "official" way to know whether the user clicked "leave" or "stay". The de facto way is to use the unload event and a setTimeout, but it's very hacky.
var internalLink = false,
stayTimeout, stayClicked;
function pageUnload() {
if(stayClicked){
// Don't run this multiple times
return;
}
if (!internalLink && location.protocol != 'http:') {
internalLink = true;
// To mark that we've ran this event once
stayClicked = true;
// If the user opted to stay, this will be ran
setTimeout(stayOnPage, 1000);
var s = 'Alert Message';
// You cannot alert or set location.href here
// This will show your message in a confirm popup
return s;
}
}
function stayOnPage(){
// The user opted to stay, do something
location.href= 'foo.com';
// If you are not going to redirect, set stayClicked to false
// otherwise leave it alone
// stayClicked = false;
}
function leavePage(){
// The user has chosen to leave the page, clear the timeout
clearTimeout(stayTimeout);
}
window.onbeforeunload = pageUnload;
window.unload = leavePage;
A much better solution would be to assign events to the <a> tags, use your own confirm box, then do whatever.
var a = document.getElementsByTagName('a');
for(var b in a){
a[b].addEventListener('click', function(e){
var c = confirm('Do you want to follow this link?');
if(c){
// The user wants to leave, let them
return true;
}
else{
// Otherwise block the link, and do whatever
e.preventDefault();
location.href= 'foo.com';
}
});
}
You have several problems in your code
1) don't hand a string to setTimeout but a function
wrong:
setTimeout("location.href= 'foo.com'", 100);
correct:
setTimeout(function(){location.href= 'foo.com'}, 100);
2) as per HTML5 spec, alert calls are allowed to be ignored in the onbeforeunload event (which apparently FF is doing).
3) Redirection is not allowed in the unload event either.
You are only allowed to return a string which is then prompted to the user (ask if they really want to leave the page). The event is cancelable, but you cannot redirect inside the event itself.
https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload

How to build the jquery/javascript to accomplish event/alert like SO's "Confirm Navigation?" [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to show the “Are you sure you want to navigate away from this page?” when changes committed?
Stackoverflow has a really interesting feature: if you start writing a new question, then you try to navigate away from the page, it will show an alert asking you confirm that you want to leave this page. This works whether you are typing a new address and entering it in the address bar, using the forward/back button, etc..
How does this work? I'd be interested to know less about the alert itself and more specifically about what event/code is triggering the alert.
Thanks!
A flag is set when the textarea is amended. The flag is checked on the unload() event of the window and the alert() is displayed if required. Something like this:
var textAmended = false;
$("textarea").change(function() {
textAmended = true;
});
$(window).unload(function() {
if (textAmended) {
alert('You started writing a question...');
}
});
More information on unload()
This is usually done by checking the value of the textarea, input etc. and changing the window.onunload function, either by passing a string or nothing, like below:
$('textarea').change(function() {
if( this.value == "" ) {
window.onbeforeunload = null;
}else{
window.onbeforeunload = "Are you sure you want to leave?";
}
});
That should trigger the built in confirm!
I think you want some confirmation on just navigating away from current window or closing it:
http://jsfiddle.net/tLWZX/
$(window).on('beforeunload', function() {
return 'You have unsaved changes.';
});
window.onbeforeunload = exit;
function exit() {
var t = 0;
$("textarea").each( function() {
var v = $(this).val();
if(v!="") {
t=t+1;
}
});
if(t>=1) {
return "You Have Some text written in textareas. Still you want to leave?";
}
}
what you wanted is in best and pure way!
http://jsfiddle.net/p4NPh/

Keep Checking until True

Basically, I have a form that is handled by a CMS which I cannot edit it's javascript, but I more or less want to add in a "Loading" or "Sending" message to my users. For example.
Currently, the default form once submitted, will append a html success message to a div called 'success' once sent, but basically, I want to run a function on the submit button that keeps checking the 'success' for anything other than '' and once it isn't empty, turn off the loading symbol.
Something like this perhaps:
$('#submitBtn').click(function(){
$('#loadingDiv').show();
while (!$('#success').html() == ''){
$('#loadingDiv').hide();
}
});
Any help would be greatly appreciated. I'm just not quite sure how to write it, I'm not great with jquery or javascript
You may do this with setInterval. Something like this:
$('#submitBtn').click(function(){
$('#loadingDiv').show();
var intervalId = setInterval(function() {
if($('#success').html() != '') {
clearInterval(intervalId);
$('#loadingDiv').hide();
}
}, 100);
});
while (!$('#success').html() == '') will freeze all other operations and will last forever.
But still - it is better to double check if you really can't add some code into success callback. Possibly ajaxComplete may help you.
Maybe you could send the form's data manually with something like this?
(In this case, maybe make sure that "submitBtn" is a simple button and not a submit button to prevent the default submit)
$('#submitBtn').click(function(){
$('#loadingDiv').show();
// Send the data with post - To complete
$.post('/your_post_addr', {data_1: my_data_1, ...},
function(data) {
$('#loadingDiv').hide();
}).error(function() {
// Your error message
alert('Error');
});
});

$.post() doesn't have time to run?

I'm trying to send data from a form to an external script prior to submitting the form, yet I cannot seem to get the data to reach the external script unless I return false; on the form itself.
$(document).ready(function () {
// Handle Form-Submission
$("#mainForm").submit(function () {
// Reset Error Array
errors = new Array();
/* Validation Code Removed - Not Relevant */
// Check if errors exist
if (errors.length > 0) {
return false;
} else {
$("div.errors").html("");
$.post("post.php",{
"First Name": name_first.val(),
"Last Name": name_last.val(),
"Home State": home_state.val(),
"Primary Email": email_primary.val()
});
}
return false; /* Remove this line, and the $.post won't work. */
});
});
I ran into the exact same problem today. Like Marc says, it's because the ajax call is asynchronous. The simplest fix is to make it synchronous.
Use .ajaxSetup() before any ajax calls like such:
$.ajaxSetup({async: false});
Sending to two end points
I would try something like this instead of using async: true. Though it is notably more complicated, it would not freeze the interface.:
$(document).ready(function(){
// Handle Form-Submission
$("#mainForm").submit(function(e){
e.preventDefault();
var $form = $(this);
if($form.data('submitting')) return; // Avoid double submissions
$(':submit').attr('disabled','disabled'); // Disable the submit button
// Reset Error Array
errors = new Array();
/* Validation Code Removed - Not Relevant */
// Check if errors exist
if (errors.length > 0) {;
$(':submit').removeAttr('disabled'); // Enable the submit button
return false;
} else {
$("div.errors").html("");
$form.data('submitting',true); // Flag that a submission has started
$.post("post.php",{
"First Name":name_first.val(),
"Last Name":name_last.val(),
"Home State":home_state.val(),
"Primary Email":email_primary.val()},
function(){
// remove our special handler and submit normally
$form.unbind('submit').submit();
}
);
}
});
});
Original Answer
It seems your hangup is that you want to use $.post if JavaScript is enabled, but let the form function normally with JavaScript disabled.
However, since none of your JavaScript will run if it is disabled you don't have to worry about altering behavior in the submit function.
You can just leave your return false; statement, or use
$("#mainForm").submit(function(e){
// all your existing code
e.preventDefault();
}
That will keep the form from submitting normally and will instead using your $.post method when JavaScript is enabled. If it is disabled it will submit normally.
preventDefault is preferred to return false if you want event bubbling to continue as normal, but keep the default browser action from continuing. return false is the equivalent of calling e.preventDefault(); e.stopPropagation();

Categories