Google Analytics Goal tracking in javascript/ajax - javascript

I have a javascript/ajax based contact form on a website page. If people click to send the form, I want this click to be registered by Google Analytics. I created a goal for this, for some reason I cannot get it to work. Any help?
The code of the form is:
<form id="footer_quick_contact_form" name="footer_quick_contact_form" class="quick-contact-form" action="includes/quickcontact.php" method="post">
<div class="form-group">
<input id="form_email" name="form_email" class="form-control" type="text" required="" placeholder="E-mail">
</div>
<div class="form-group">
<textarea id="form_message" name="form_message" class="form-control" required placeholder="message" rows="3"></textarea>
</div>
<div class="form-group">
<input id="form_botcheck" name="form_botcheck" class="form-control" type="hidden" value="" />
<button type="submit" class="btn btn-default btn-transparent text-gray btn-xs btn-flat mt-0" data-loading-text="One moment please...." onClick="ga('send', 'event', { eventCategory: 'Contact', eventAction: 'ContactRequest'});">Verstuur nu!</button>
</div>
</form>
<!-- Quick Contact Form Validation-->
<script type="text/javascript">
$("#footer_quick_contact_form").validate({
submitHandler: function(form) {
var form_btn = $(form).find('button[type="submit"]');
var form_result_div = '#form-result';
$(form_result_div).remove();
form_btn.before('<div id="form-result" class="alert alert-success" role="alert" style="display: none;"></div>');
var form_btn_old_msg = form_btn.html();
form_btn.html(form_btn.prop('disabled', true).data("loading-text"));
$(form).ajaxSubmit({
dataType: 'json',
success: function(data) {
if( data.status == 'true' ) {
$(form).find('.form-control').val('');
}
form_btn.prop('disabled', false).html(form_btn_old_msg);
$(form_result_div).html(data.message).fadeIn('slow');
setTimeout(function(){ $(form_result_div).fadeOut('slow') }, 6000);
}
});
}
});
</script>
As you can see I added an on-click event to the send button. In google analytics I created a goal, by going to admin>goals>new goal>custom radio button>next. I gave the goal a name, selected the Event radio button and filled in the following fields:
Category: Contact
Action: ContactRequest
Label: Empty
Value: Empty
I thought I'd have fixed it, but until now I can't track any results in GA. Any suggestions?

After reading your comment it would seem the problem is that you are using the wrong syntax in your click event handler.
You are calling the ga() function, which is a part of the Universal Analytics Code, which for some time now has been replaced by gtag.js.
I do not usually use gtag.js (I prefer to use Google Tag Manager), but according to the documentation the correct call would look like this:
gtag('event', 'contact_request', { // second parameter is event action
'event_category': 'contact',
'event_label': '',
'value': 0
});
(Actually you can leave out label and value if you do not need them).

Related

Submitting a form after validating with jquery validator on a button not in form tag

I have been battling with what is wrong on this code since. It so happens that the form is not submitting on this button. The button is of type button and not in the form tag.
$("#step1Btn").click(function () {
var userForm = $("form[name='step1Form']");
if (userForm.valid()) {
userForm.submit(function () {
console.log('submitted o!')
$("#spin1").show();
$("form[name='step1Form'] > span").remove();
$('input[name="emailInput"]').prop('name', "id")
$('input[name="fullNameInput"]').prop('name', "full-name")
$('input[name="phoneInput"]').prop('name', "phone-number")
$.ajax({
type: 'POST',
url: "api/v1/user?" + $(this).serialize(),
success: (result) => {
localStorage.setItem('user', JSON.stringify(result))
localStorage.setItem('authToken', result.authToken);
$("form[name='step1Form'] > span").remove()
$('#step1, #step2').toggle();
$('#step1Title, #step2Title').toggle();
},
error: function (request, exception, errorThrown) {
$("form[name='step1Form'] > span").remove();
$("form[name='step1Form']").prepend('<span class=\'error\'><p>' + request.responseJSON.message + '</p></span>')
},
})
});
} else {
return false;
}
});
Below is the complete form
<div id="step1" class="col-12 col-md-6">
<form name="step1Form">
<div class="home-icon d-flex justify-content-center align-items-center flex-column">
<img src="images/new-icons/user.png" alt="User Registration logo" height="80" />
<p class="my-3">User Registration</p>
</div>
<div class="form-group">
<label for="fullNameInput">Contact full name</label>
<input name="fullNameInput" class="form-control custom-input" placeholder="First name Last name" id="fullNameInput">
</div>
<div class="form-group">
<label for="emailInput">Contact email address</label>
<input name="emailInput" type="email" placeholder="example#email.com" class="form-control custom-input" id="emailInput">
</div>
<div class="form-group">
<label for="confirmEmailInput">Confirm contact email address</label>
<input name="confirmEmailInput" type="email" placeholder="example#email.com" class="form-control custom-input"
id="confirmEmailInput">
</div>
<div class="form-group">
<label for="phone">Contact phone number</label>
<input name="phoneInput" placeholder="08012345678" class="form-control custom-input" id="phone">
</div>
</form>
<button type="button" class="btn red-btn user-btn custom-btn" id="step1Btn">Next<i id="spin1" class="fa fa-spinner fa-spin"></i></button>
</div>
So I would like to see where I went wrong. I am able to log and see output whenever i place a console.log in between the if(userForm.valid) and the userForm.submit().
But as soon as i place it in the userform.submit() I do not get any value back. Like, the form is totally not submitting. I dont know if its because of how I made my Ajax call.. Please Help
You're putting Ajax inside of a submit....
$("#step1Btn").click(function () {
....
if (userForm.valid()) {
userForm.submit(function () {
....
$.ajax({ ....
Which makes no sense since Ajax replaces the actual submit. By doing this you are effectively sending it through validation again; I can't see the .validate() method, but suspect that you are simply using the default option, which would be yet another regular submit... you're probably stuck in a loop going nowhere.
The best place for your Ajax would be inside the submitHandler of the .validate() method.
If your button is outside of the form, you capture the click and manually trigger a submit, which then lets the validation plugin take over the rest.
$("#step1Btn").click(function () { // click of external button
$("form[name='step1Form']").submit(); // trigger validation & submission
});
$("form[name='step1Form']").validate({ // initialize plugin
submitHandler: function(form) { // fires when valid
// YOUR AJAX GOES INSIDE HERE
return false;
},
// other options, rules, etc.
});
Read the documentation for the submitHandler.

How to show a blue colored progress bar exactly like gmail's horizontal blue colored progress bar which is displayed when user submits the form?

I'm using Bootstrap v3.3.5 in my website.
In one scenario I'm displaying a form in Bootstrap modal dialog. User fills in the data and submits the form. After submitting the form the form looks as it is until the response is received from the server.
So, what I want to do is display a blue colored horizontal progress bar exactly resembling the blue colored horizontal progress bar which gmail uses when it loads the inbox mail list after login. This progress bar should be dynamic like gmail's progress bar(i.e. progressive in nature and not like revolving circle loader image).
It should be displayed at the top of form with the message "Please wait...your event is being generated." I've added a comment in my code telling where it should be displayed exactly.
Following is my Bootstrap modal's HTML code:
<form method="post" action="{$site_url}add_event.php" id="formAddEvent" >
<!-- The gmail look alike loader should display here only upon successfull submission of a form. -->
<div class="form-group" id="addEventErrorMsg" style="display:none; color:#FF0000;">
</div>
<div class="form-group">
<input type="text" name="txt_event_title" id="txt_event_title" autocomplete="off" class="form-control custom-height" placeholder="Event Title" style="height:30px;" />
</div>
<div class="form-group">
<textarea type="text" name="txt_event_description" id="txt_event_description" autocomplete="off" class="form-control custom-height" placeholder="Description (optional)" style="height:60px;" ></textarea>
</div>
<table border="0" cellspacing="10">
<tr>
<th><span class="event-title1" style="margin-bottom:5px;">Start Date:</span></th>
<th><span class="event-title1" style="margin-bottom:5px;">End Date:</span></th>
</tr>
<tr>
<td>
<div style="margin-right:15px;" class="form-inline form-group event-selection">
<div class="form-group has-feedback">
<div class='input-append date form_datetime' data-date="2013-02-21T15:25:00Z">
<input type='text' id='event_start_date' name="event_start_date" style="width:225px; display:inline; height:30px;" class="form-control" autocomplete="off" />
<span aria-hidden="true" class="glyphicon glyphicon-calendar form-control-feedback"></span>
</div>
</div>
</div>
</td>
<td>
<div class="form-inline form-group event-selection">
<div class="form-group has-feedback">
<div class='input-append date form_datetime' data-date="2013-02-21T15:25:00Z">
<input type='text' id='event_end_date' name="event_end_date" style="width:225px; display:inline;height:30px;" class="form-control" autocomplete="off" />
<span aria-hidden="true" class="glyphicon glyphicon-calendar form-control-feedback"></span>
</div>
</div>
</div>
</td>
</tr>
</table>
<div class="form-group has-feedback">
<input type="text" name="txt_event_location" id="txt_event_location" autocomplete="off" class="controls form-control custom-height" placeholder="Event Location" style="height:30px;" />
<span class="glyphicon glyphicon-map-marker form-control-feedback" aria-hidden="true"></span>
</div>
<div style="clear:both;"> </div>
<div id="map"></div>
<div class="form-group">
<input type="text" name="txt_event_room" id="txt_event_room" autocomplete="off" class="form-control custom-height" placeholder="Room No." style="height:30px;" />
</div>
<div class="form-group">
<div id="custom-templates">
<input class="typeahead form-control custom-height" id="selected_groupname" name="selected_groupname" type="text" placeholder="Invite Group" value="{foreach from=$user_group_list1 item=grouplist key=key} {if $groupId==$grouplist.page_id} {$grouplist.title} {/if} {/foreach}">
<input type="hidden" name="selected_groupid" id="selected_groupid" value="" />
</div>
</div>
<div class="modal-footer text-center">
<button class="btn btn-primary" id="btn_add_event" type="button">Add Event</button>
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
</div>
</form>
The function which gets called for form submission upon clicking on button with id btn_add_event is as follows:
$(document).ready(function() {
$("#btn_add_event").click(function() {
var strSeriaze = $( "#formAddEvent" ).serialize();
url = $( "#formAddEvent" ).attr('action');
$("#btn_add_event").attr('disabled', 'disabled');
$("#addEventErrorMsg").html('');
$.ajax({
url : url,
type : "POST",
data : {postData:strSeriaze},
beforeSend: function() {
$('#loader-icon').show();
},
complete : function() {
$('#loader-icon').hide();
},
success : function(data) {
// $("#events-result").append(data);
$('#loader-icon').hide();
if(data == true) {
$("#myModal-add-event").modal('hide');
$("#myModal-add-event").hide();
//window.location = site_url + "event_index.php";
window.location.href = site_url + "event_index.php";
return false;
} else {
$("#btn_add_event").attr('disabled', false);
$("#addEventErrorMsg").show();
$("#addEventErrorMsg").html(data);
}
},
error: function() {}
});
})
});
Please help me. Thanks.
My question is different than any other question. I don't know how to work the progress bar percentage or progress with the response time. I'm not getting solution for it from anywhere. Please remove the tag of duplicate from my question.
My question is different than any other question. I don't know how to
work the progress bar percentage or progress with the response time.
I'm not getting solution for it from anywhere. Please remove the tag
of duplicate from my question.
No it's not different, and therefore it is duplicate of
show progressbar while loading pages using jquery ajax in single page website
The only difference is that in your bounty notice you said
This question had a bounty worth +50 reputation from user2839497.
The question is widely applicable to a large audience. A detailed
canonical answer is required to address all the concerns.
I want a canonical answer for this question. I want a working demo of
a code which must be integrated with the code I posted in the
question. I need the entire working code demo(jsfiddle) for the same.
I don't want any reference links for tutorials or anything else. I
just want to work the exactly same google styled blue colored progress
bar working in my website's ajax function call. Anyhow you make my
code working with the necessary other code. Thanks. Waiting keenly for
the perfect answer folks. Have a nice day.
and as SO is not a code factory to its users disposal, the dupe is an excellent way to solve your question.
This community answer is intended to be deleted when the question is closed as a duplicate.
Edit after post review
This code snippet shows the essential part for a progress bar.
HTML
<div class="progress-bar"></div>
Script
function set_pbar(p) {
$('.progress-bar').css({ width:(p * 100)+'%'});
}
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
//Sending in progress, divided with 2 make bar 50% wide after sending
set_pbar(evt.loaded / evt.total / 2);
}
}, false);
xhr.addEventListener("progress", function(evt){
if (evt.lengthComputable) {
//Receiving in progress, dividing with 2 and adding 0.5 make bar start at 50%
set_pbar(0.5 + (evt.loaded / evt.total / 2));
}
}, false);
return xhr;
},
url: "/echo/json/",
type: 'POST',
data: {json: JSON.stringify(new Array(100000))},
success: function(data){
//Loaded...
}
});

How to add before send function to current return ajax function?

i have a main form on my main page, the form get an email address from the user and check if the email exist.
My target is to show the results on the same page with bootstrap collapse.
I am using this code in the javascript side:
$(".emailCheckForm").bind("submit", function () {
return $.ajax({
type: "POST",
width: "auto",
height: "auto",
padding: 10,
cache: !1,
url: "_/php/checkemail.php",
data: $(this).serializeArray(),
success: function (t) {
$(".res").append(t).collapse();
},beforeSend: function(){
$( "#message" ).empty();
}
}), !1
}),
my html code:
<form action="" method="post" class="col-md-8 centered emailCheckForm">
<div class="input-group">
<input type="email" name="email" class="form-control checkFrame" placeholder="you#youremail.com">
<div class="input-group-btn">
<input type="submit" value="answer me!" class="btn btn-default checkFrame" tabindex="-1" />
</div>
</div><!-- /.input-group -->
</form>
<div class="res"></div>
Now this working but the problem is that if i want to check another email i get the same results until i will refresh the page.
So i want to implement a before send function that will remove\empty the div results.
I cant make this happen because that every time that i insert the beforsesend function the post not working, any suggestions to make proccess like that in the right way?
How about this one. On every successful callback it will clean up results from previous request and re-populate latest:
...
success: function (t) {
$(".res").empty().append(t).collapse();
}
...

js event handler does not intercept form submission (Mixed Active Content)

-- EDIT: This turns out not to be a js issue but a "Mixed Active Content" issue in Firefox 24.0. --
Locally, an event handler correctly intercepts a form submission; however, on Heroku, the application instead issues an HTTP request and the appropriate Javascript function is never called.
My webpage has the following Javascript:
<script id="infrastructure-cxn" type="application/javascript">
$(function () {
// [additional code ... ]
$("#message-form").submit(function (event) {
event.preventDefault();
var msg = $("#msg-input").val();
var msgObject = { text: msg };
server.publish(channel, msgObject);
});
});
</script>
My webpage has the following form:
<form id="message-form" accept-charset="UTF-8">
<!-- [additional code ...] -->
<div class="field">
<input
id="msg-input"
type="text"
placeholder="Enter message..." />
</div>
<input
class="btn btn-xs btn-primary"
type="submit"
value="Send" />
</form>
Could anyone offer any suggestions as to how I can fix my application so that in production it doesn't issue either GET or POST requests but instead calls the anonymous function in my event handler?

How to Login by filling the form in CasperJs

Following is the hlml of the login form that I have
<div class="login_area_user">
<form method="post" action="https://www.tradus.com/login?dest_url=https://www.tradus.com/cart/select-address" id="user-login">
<input type="hidden" value="1" name="form_submit">
<h3 style="display:inline-block;">Already a Member</h3>
<p id="login-main-center-right-descp">You can use tradus login id and password</p>
<div class="login-row">
<label class="colorBlack">Email / Login*</label>
<input class="login-field" type="text" name="name" id="edit-namepopup">
</div> <!-- [/login-row] -->
<div class="login-row">
<label>Password</label>
<input class="login-field" type="password" id="edit-passpopup" name="pass">
</div> <!-- [/login-row] -->
<div class="login-row">
<a class="forgotPassword" href="/forgot_password">Forgot your password?</a>
<!--input type="checkbox" name="remember" /><span>Remember me</span-->
</div>
<div class="login-row">
<input class="login-button" value="Login" type="submit">
</div>
<input type="hidden" name="op" value="Log in">
</form>
</div>
Am using the following code to login :
this.fill('form#user-login', {
'form_submit': 1,
'name': 'abc#gmail.com',
'pass': 'pwd',
'op': 'Log in'
}, true);
But I dont thing its doing the thing for me.
casper.waitForSelector("form input[name='name']", function() {
this.fillSelectors('form#user-login', {
'input[name = name ]' : 'abc#gmail.com',
'input[name = pass ]' : 'pwd'
}, true);
});
Simply use this (see waitForSelector docs).
Firstly, wait for the form to be loaded.
Then fill the form using the selectors.
casper.waitForSelector('form', function(){
this.fill('form', {
'name': 'abc#gmail.com',
'pass': 'pwd'}, true);
});
<!-- wait until a form tag disappears -->
casper.waitWhileSelector('form', function(){
this.echo('selector is no more!');
});
casper.then(function(){
this.echo(this.getTitle());
});
In case anyone else finds this.. I used some combination of these answers - my login form was also in an iframe which added some difficulty, but basically the issue I saw (cookie-based login) is that casper was going to the next step before the server could respond and set the cookie. I added some .wait() callbacks to ensure enough time to get that cookie. It may not be foolproof, but I have yet to have an issue with it
Mind you, the cookie needs to be set EVERY CRAWL
casper.start(config.loginUrl, function() {
console.log("Checking login status # " + config.loginUrl);
// set a wait condition to make sure the page is loaded (particularly iframe in my case)
this.wait(5000,function(){
// switch to iframe (won't be necessary for most)
this.page.switchToChildFrame('login');
// fill out the form
this.fillSelectors("form[name='loginForm']",{
'input#txtUsername' : config.username,
'input#txtPassword' : config.password
});
// click the login button
console.log("Logging In...")
this.click('input.button.login');
// ** give my crappy dev server 5 seconds to respond
this.wait(5000,function(){
console.log('Starting to spider ' + dataObj.start)
// do yo dance
spider(dataObj.start);
});
Hmmm.. Follow that with:
casper.then(function () {
this.evaluate(function () {
$('form#user-login').submit();
});
});

Categories