I know that this question may not be fit for stack overflow. I've been searching for an example on how to use the ajax helper but most toturials have only gone through the helper and they have not provided any practical example. I already know how to make use of ajax the javascript way but just want to know how I can use the ajax helper that microsoft has provided.
To describe how this GitHUb branch works:
First, let's define an action we're going to request. To keep things simple, let's just make a very basic POST action:
//
// POST: /Home/Ajax
[HttpPost]
public PartialViewResult Ajax()
{
// use partial view so we're not bringing the entire page's theme
// back in the response. We're simply returning the content within
// ~/Views/Home/Ajax.cshtml
return PartialView();
}
Next, setup a destination for your content and give it an id (here I've named it "update-me"):
<div class="well" id="update-me">
Click the button to see some AJAX content.
</div>
Moving on from there we setup the form. The below demonstrates the standard AJAX functionality, but you could bind your own functions to some of the events specified by AjaxOptions.
#using (Ajax.BeginForm("Ajax", new AjaxOptions {
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace, // empty the target first
UpdateTargetId = "update-me" // place content within #update-me
}))
{
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-refresh"></i>
Click Me!
</button>
}
And finally, we need to specify our script libraries responsible for most of the ["automatic"] wiring up of the form functionality:
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
That's it. As you begin playing with it you'll find it's pretty simple to extend it. For example, if you wanted to show a "working" icon you could specify custom functions in the OnBegin and OnComplete properties.
Ajax helper of ASP.NET MVC essentially provides Ajax functionality to your web applications. AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs request asynchronously. Using Ajax helper you can submit your HTML form using Ajax so that instead of refreshing the entire web page only a part of it can be refreshed. Additionally, you can also render action links that allow you to invoke action methods using Ajax. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvc.Ajax namespace.
AJAX-enabled link based on action/controller example:-
Following example shows how to use AJAX action link using action and controller in Asp.Net MVC.
#Ajax.ActionLink("Fatch Data", "GetData", new AjaxOptions {UpdateTargetId = "Data-container", HttpMethod = "GET" })
Here is the html output of above code block.
Output:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#Data-container" href="/Home/GetData"> Fatch Data </a>
Do you know Unobtrusive AJAX in MVC?
The Unobtrusive Validation and AJAX support in ASP.NET MVC follow many best practices that enable Progressive Enhancement and are also super easy to use. The unobtrusive AJAX library (not the unobtrusive validation library) is admittedly a bit limited in functionality, but if it satisfies the requirements of the application you are writing, then by all means use it. And because the source code of it is in your app (it's JavaScript, after all), it's generally straightforward to make any updates or changes to it as you see fit.
I have a website that I am using the new Universal Analytics (analytics.js) to track. Everything is setup and working (pageviews, referrals, etc.) using the following code snippet:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-39570713-1', 'site.com');
ga('send', 'pageview');
</script>
That is located before the </head> tag.
I am using JQuery to fire off an event. I tested the JQuery with an alert message and it is getting called, so that isn't the problem. Here is the snippet that fires when a button is clicked:
$('#submitButton').on('click', function() {
ga('send', 'event', 'button', 'click', 'contact form');
});
Nothing is appearing in the Events section of Analytics. I keep clicking the button, even from different computers just to make sure it isn't excluding my IP address. Because the Analytics doc that Google provides does not provide a whole lot of explanation I'm at a loss here.
If you are using Google Tag Manager and also want to trigger some events via code, ga('send'...) does not appear to be enough. You need to first fetch the appropriate analytics object:
if ("ga" in window) {
tracker = ga.getAll()[0];
if (tracker)
tracker.send("event", "Test", "Test GA");
}
Note that this assumes you're only using a single Google Analytics Tracking code on your site. If you happen to be using multiple, you may need to fetch the appropriate one by name or index.
New version of analytics has a new syntax. Replace the line below;
ga('send', 'event', 'button', 'click', 'contact form');
with this;
gtag('event', 'click', {'event_category' : 'button',
'event_label' : 'contact form'});
Reference;
https://developers.google.com/analytics/devguides/collection/gtagjs/events
For testing purposes you could also use the hitCallback method:
ga('send', {
'hitType': 'event',
'eventCategory': 'button',
'eventAction': 'click',
'eventLabel': 'contact form',
'hitCallback' : function () {
alert("Event received");
}
});
Update: comma was missing.
For GA for this moment...
Sending a new page in SPA looks finally like this for me:
if (window.ga){
window.ga.getAll()[0].set('page', location);
window.ga.getAll()[0].send('pageview')
}
This shows exactly what wanted on GA reports like a new page is hit and the title and all are correct.
In my case the problem was uBlock Origin that was blocking the analytics script from loading.
I had the exact same problem. I had to create a new property and select "Universal Analytics" instead of "Classic Analytics" (it is labeled as "beta"). Now events are captured properly.
I had this same problem, and I think I've found the solution, but it really leaves a bad taste in my mouth about Universal Analytics.
What I had to do was explicitly use the synchronous analytics API. So instead of including the usual snippet in your <head> tag, use the following code:
<script src="//www.google-analytics.com/analytics.js"></script>
<script>
tracker = ga.create('UA-XXXXXXX-1', 'example.com');
tracker.send('pageview');
</script>
Then you call the event tracking code like this:
tracker.send('event', 'Category', 'Action', 'Label');
This will ensure that the tracking beacon is sent to Google and acknowledged before the page the user navigated to starts loading.
This suggests that Universal Analytics requires some kind of additional acknowledgment beyond what the old ga.js analytics code required. So when you attach an event to a click that brings the user to another page, that acknowledgement can't be sent because the browser has left the page and dropped the current javascript execution stack.
Maybe this problem is specific to certain execution environments (I'm using Chrome 34 on OSX Mountain Lion), which might explain why more developers aren't noticing this problem.
today I needed to setup analythics for the first time and I found myself in the same trouble.
I found that the bast way to deal with the multiple trackers to avoid the getAll(), is this:
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-xxxxxx-y', 'auto', 'tracker');
ga('tracker.send', 'pageview');
ga('tracker.send', 'event', 'test', 'click', 'automaticEvent')
Note that you have to pass a "name" to the create method, and then you send an event to that tracker with ga([trackerName].send, ...)
Reference: https://developers.google.com/analytics/devguides/collection/analyticsjs/accessing-trackers
If anyone is trying to send an event to Google Analytics and wondering why the send function is doing nothing without any clear hint, I recommend using the debug version of their library. It will log some useful hints in the browser console.
Instead of getting the script from https://www.google-analytics.com/analytics.js, get it from https://www.google-analytics.com/analytics_debug.js. I found this out from their documentation.
I cannot see anything wrong with the code itself. Have you tried using the alternative event tracking?
ga('send', {
'hitType': 'event', // Required.
'eventCategory': 'button', // Required.
'eventAction': 'click', // Required.
'eventLabel': 'contact form'
});
I would also suggest testing the website with GA Debug Chrome addon, which allows you to see the tracking beacon was sent or not.
"Official" debugging documentation for Universal Analytics is still missing as of now, but hopefully it will be added soon as ga_debug.js provides lot of useful ways how to find out what's wrong with Analytics implementation...
I have the same problem, and it looks like events are tracked, but GA dashboard doesn't allow to browse them. This is the only way how I could interprete the "Visits with events: 1071" but "Total events: 0" that GA dashboard shows me.
UPD: With GA Chrome debug, have found a problem; 1st method is not working (sends the event without any data attached), but the 2nd one is OK.
You should also consider that it is likely that the page gets reloaded after the submit event was fired before the ga script was able to execute the 'send' method. To avoid this you could employ the 'hitCallback' mechanism, i.e. prevent the submit, call the ga send-method and submit the form data in the callback.
I got it working - my example is using the new Universal Analytics.
<script type="text/javascript">
function sliderOnChange() {
var period = window.convertDays(($("#PeriodSlider").slider("value")));
var amount_of_credit = $("#AmountOfCreditSlider").slider("value");
var gaEventInput = "£" + amount_of_credit + " for " + period;
ga('send', 'event', 'slider', 'sliding', gaEventInput);
}
</script>
Make sure Google Analytics / Google Tag Manager filters are not excluding any traffic from different domain. (Maybe you are testing it to get this working using different domain)
Recheck your GA id and domain in ga('create', 'UA-39570713-1', 'site.com');
Create a new profile in Google Analytics (GA) for testing purposes and debug your html in the same domain you define in GA.
Change the date to be today in GA - you might also need to wait some time before it appears in GA
I recommend sending GTM event via window.dataLayer.push({ event: 'EVENT_NAME', ...data }) and in GTM creating a trigger to fire a tag which sends event to Google Analytics. You'll have the best debugging experience with GTM preview and you'll be sure that events will be sent from GTM to GA, because GTM takes care of that.
onclick ga() function not working for me, I have also added the 'analytics.js' in <head> section -
<a mat-list-item routerLink='/dashboard' onclick="ga('send', 'event', 'Dashboard', 'Click', 'demoClick, 30);">
<mat-icon color="accent">home</mat-icon>
<span class="side-item">Dashboard</span>
</a>
gtag() function working fine for me, only the 'gtag.js' added in <head> section, 'analytics.js' not required or can be removed -
<a mat-list-item routerLink='/dashboard' id="sideNavDashboard" onclick="gtag('event', 'Click', {'event_category':'Dashboard', 'event_label':'demoClick', 'value':'30'});">
<mat-icon color="accent">home</mat-icon>
<span class="side-item">Dashboard</span>
</a>
Result (Google Analytics output) -
I was seeing everything except Events (both real-time and report). My steps included:
Calling Google and they found out that my GTM tag for Google Optimize was stopping all events to be sent to Analytics.
Removed the Optimize tag from Google tag manager and events started popping up in Analytics.
Try pausing some tag if you have this issue. Also connect the event tag to some goal.
I am using Vue.js and it seems I have to create ga each time, even though it was already created on the window:
ga('create', yourGtagId, 'auto');
ga('send', {});
In my case it didn't work because I loaded the HTML file directly from the file system.
Loading the page via a web server did the trick.
For local development a tool like https://github.com/tj/serve does a great job.
The only way I solved the problem was rolling back to the previous version of Analytics (non-beta):
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-39570713-2']);
_gaq.push(['_setDomainName', 'optimino.com']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
You can also use a jquery plugin I wrote for the new Universal Analytics:
https://github.com/pascalvgemert/jquery-analytics-event-tracking
I thought this was pretty straight forward but I don't get the same results as the tutorials I read. I have a button on an html page that calls a function in script tags. I also have a reference to the prototype.js file which I haven't even begun to implement yet. If I leave that reference in the page, my function call does not work from the button's onclick event. Below is what is called from the button onclick event.
callIt = function(){
alert('It worked!');
}
</script>
A couple of things: first, make sure your HTML is valid. Run it through the validator at http://validator.wc.org.
Next, once you're sure that your page is valid, add the prototype.js library as the first script reference on the page:
<script type="text/javascript" src="prototype.js"></script>
Notice that I didn't close it like this <script ... /> Script blocks need to have an explicit closing tag (at least in XHTML 1.0 Transitional)
Now, to answer your question, I'm really not sure what you're asking, but if you wanted to attach the callIt method to the onclick handler of your button using Prototype, then do this:
Event.observe(window, 'load', function() {
Event.observe('button_id', 'click', callIt);
});
Put this in script tags in the element of the page, below the prototype script reference. This will execute when the DOM is loaded & the button exists on the page.
Hope this helps.
That worked. I'm just puzzled why none of the examples I have been working from have done this.
Thanks!