How to get Total Results using Google Analytics Embed API - google-analytics

I'm trying to simply pull the total number of pages on my site.
Using the GA Query Explorer (https://ga-dev-tools.appspot.com/query-explorer/), you can see the "Total results found" number when the results are displayed after running a query.
How can I apply this to GA Embed API query format? ...
var pageTitles = new gapi.analytics.googleCharts.DataChart({
reportType: 'ga',
query: {
'dimensions': 'ga:pageTitle',
'metrics': 'ga:pageviews',
'segment': 'gaid::-1',
'sort': '-ga:pageviews',
'filters': 'ga:pagePath!=/',
'max-results': '10',
'totalResults': 'integer',
},
chart: {
type: 'TABLE',
container: 'page-titles',
options: {
title: 'Top Pageviews',
width: '100%'
}
}
});
Thank you!!

If you add an event handler for successful queries, you can get access to the totals. Here's an example:
var pageTitles = new gapi.analytics.googleCharts.DataChart({
query: {
'dimensions': 'ga:pageTitle',
'metrics': 'ga:pageviews',
'segment': 'gaid::-1',
'sort': '-ga:pageviews',
'filters': 'ga:pagePath!=/',
'max-results': '10'
},
chart: {
type: 'TABLE',
container: 'page-titles',
options: {
title: 'Top Pageviews',
width: '100%'
}
}
});
pageTitles.on('success', function(result) {
// Print the total pageview count to the console.
console.log(result.response.totalsForAllResults['ga:pageviews']);
});
And here's the documentation for the parameters passed to the 'success' event:
https://developers.google.com/analytics/devguides/reporting/embed/v1/component-reference#datachart
Also note that you don't need the 'totalResults': 'integer' part that you have in your example, nor do you need the reportType: 'ga' part (it's optional).

Related

Some Dimensions Cause Empty Response for GA4 runReport API

I believe this is a regression and used to work, but when I make queries against the GA4 RunReport API and request data which includes the dimensions "source", "medium" or "defaultChannelGrouping" I get a 200 from the server with no rows.
For Example:
const dimensions = ['browser', 'source'];
const basicDataMetrics = ['sessions'];
const body = {
dimensions: dimensions.map((z) => { return { name: z } }),
metrics: metrics.map((z) => { return { name: z } }),
dateRanges: [
{
endDate: dateToQuery,
startDate: dateToQuery
},
],
offset: startIndex,
limit: maxResults,
keepEmptyRows: true,
returnPropertyQuota: true
}
const ga4Response = await axios.post(`https://analyticsdata.googleapis.com/v1beta/properties/${webPropertyId}:runReport`, body, { headers });
In the above example, gaResponse.data will have something like
{
dimensionHeaders: [
{
name: "browser",
},
{
name: "source",
},
],
metricHeaders: [
{
name: "sessions",
type: "TYPE_INTEGER",
},
],
metadata: {
currencyCode: "EUR",
timeZone: "Europe/Paris",
},
kind: "analyticsData#runReport",
}
Notice the completely missing rows or rowCount. If I omit 'source' from my dimensions everything works as expected. I've noticed that 'medium' and 'defaultChannelGrouping' also cause this behavior. All of these dimensions used to be valid and are still valid accoring to the documentation . Does anyone know what I can do to get results for these dimensions? Are they deprecated for this API?
If your GA4 property's Reporting Attribution model is neither Cross-channel last click nor Ads-preferred last click, then event-scoped attribution dimensions like "source", "medium", and "defaultChannelGrouping" return data for only conversion events. Attribution models are explained some on About attribution and attribution modeling.
Try using "sessionSource", "sessionMedium", or "sessionDefaultChannelGrouping" in your request. If you use "sessionSource", your example request will return rows if at least one session occured on your GA4 property in the date range.

Fullcalendar V4: How to parse json received from ajax into event list

I'm trying to retrieve a list of events from an ajax call. I use the following code.
document.addEventListener("DOMContentLoaded", function()
{ var calendarEl = document.getElementById("id_d_agenda_1");
var calendar = new FullCalendar.Calendar(calendarEl, {
plugins: [ 'interaction', 'dayGrid', 'timeGrid', 'list' ],
header: {
left: 'prev,next today',
center: 'title',
right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek'
},
defaultDate: '2019-08-12',
editable: true,
navLinks: true, // can click day/week names to navigate views
eventLimit: true, // allow "more" link when too many events
selectMirror: true,
select: function(arg) {
var title = prompt('Event Title:');
if (title) {
calendar.addEvent({
title: title,
start: arg.start,
end: arg.end,
allDay: arg.allDay
})
}
calendar.unselect()
},
events: function(arg) {
$.ajax({
url: 'd.php',
dataType: 'json',
data: {
cmd:'getdata',
start:arg.startStr,
end:arg.endStr,
tz:arg.timeZone,
component:'d_agenda_1',
},
success: function(doc) {
$(doc).each(function() {
calendar.addEvent( this );
})
}
})
}
})
calendar.render();
});
While debugging my javascript I can see the rows of events appear in 'doc'. First I tried to bulk add them to the agenda, but that didn't seem to work. Now I'm adding them one-by-one, buth they still don't appear. I have checked the this variable in the debugger and it shows a single event:
title:"value", start:"2019-08-01". In fact I'm using the sample list that comes with the package. Can someone point me to the right direction in what I'm doing wrong?
other options I tried (with no luck ;-):
I tried to leave the jquery out, but with similar effect:
success: function(doc) {
doc.forEach(function(value) {
calendar.addEvent( value );
})
}
success: function(doc) {
$(doc).each(function() {
calendar.addEvent({
title:this.title,
start:this.start
});
})
Not sure if it's helpful, but I added the selectable option and tested the select option. The calendar.addevent on the select: doesn't add the event either. Since this is copied from the sample i'm quite confused now. Fun part is that if you replace the ajax part with a regular [] expression that all works well. Even the selectable options, so there's definitely something wrong with my ajax implementation, in regards to this component.
According to the DOCS you need to have a successCallback that will return the events to the calendar.
Here is the docs https://fullcalendar.io/docs/events-function
Here is a simple Demo https://codepen.io/nasser-ali-karimi/pen/gOOJrWV?editors=0010
And in short, I can say that you need to set the events like this.
events: function(info, successCallback, failureCallback) {
successCallback([
{"resourceId":"a","title":"event 1","start":"2019-11-23","end":"2019-11-25"},
{"resourceId":"b","title":"event 3","start":"2019-11-24T12:00","end":"2019-11-25T06:00"},
{"resourceId":"b","title":"event 4","start":"2019-11-24T07:30","end":"2019-11-24T09:30"},
{"resourceId":"b","title":"event 5","start":"2019-11-24T10:00","end":"2019-11-24T15:00"},
{"resourceId":"a","title":"event 2","start":"2019-11-24T09:00","end":"2019-11-24T14:00"}
])
}
you didn't mention the events data that comes from Ajax request, so I can say you need to provide the data like what said on docs.
Addition
Note: Event's date are on 11/28 and 11,29 so navigate to those dates to see the events.
Demo https://codepen.io/nasser-ali-karimi/pen/qBBGVbG?editors=0010
events: function(info, successCallback, failureCallback) {
var arrevents = [];
jQuery.get( "https://api.myjson.com/bins/16ubhe", function( data ) {
// var response = JSON.parse(data);
// $.each(response, function(k, v) {
// arrevents.push(v);
// });
arrevents = data;
successCallback(arrevents);
});
},

Google Analytics API return multiple landing pages data

Can anyone help me out with this? I need to use the GA api to return data of multiple landing pages. Data such as page views, bounce rate, avg time on page, etc.
So far I've managed to return the data for 1 page when this is set in the filters. Is there anyway to do this for multiple pages in 1 request?
// Google API Library
(function(w,d,s,g,js,fjs){
g=w.gapi||(w.gapi={});g.analytics={q:[],ready:function(cb){this.q.push(cb)}};
js=d.createElement(s);fjs=d.getElementsByTagName(s)[0];
js.src='https://apis.google.com/js/platform.js';
fjs.parentNode.insertBefore(js,fjs);js.onload=function(){g.load('analytics')};
}(window,document,'script'));
gapi.analytics.ready(function() {
var CLIENT_ID = clientID
var VIEW_ID = viewID;
gapi.analytics.auth.authorize({
container: 'auth-button',
clientid: CLIENT_ID
});
var query = {
ids: VIEW_ID,
metrics: 'ga:sessions,ga:pageviews,ga:avgTimeOnPage,ga:bounceRate',
dimensions: 'ga:date',
filters: 'ga:pagePath=#page1' //<-- page name to search for
}
var report = new gapi.analytics.report.Data({ query });
report.on('success', function(response) {
console.log(response);
});
report.execute();
});
Add ,ga:pagePath=#page2 in filters for get also the data of the second page and add ga:pagePath in dimensions for separate the two pages in the result.
var query = {
ids: VIEW_ID,
metrics: 'ga:sessions,ga:pageviews,ga:avgTimeOnPage,ga:bounceRate',
dimensions: 'ga:date,ga:pagePath',
filters: 'ga:pagePath=#page1,ga:pagePath=#page2' //<-- page name to search for
}
For new GA v4, you can pass page paths as array to inListFilter under dimensionFilter
const response = await analyticsDataClient.runReport({
property: `properties/${`xxxxxxxx`}`,
dateRanges: [
{
startDate: startDate,
endDate: "today",
},
],
dimensionFilter: {
filter: {
inListFilter: {
values: pagePathsArr,
},
fieldName: "pagePath",
// stringFilter: {
// value: slug,
// },
},
},
dimensions: [
{
name: "pagePath",
},
],
metrics: [
{
name: "screenPageViews",
},
],
});

dgrid JsonRest store not working

I have the following:
require([
"dojo/dom",
"dojo/on",
"dojo/store/Observable",
"dojo/store/JsonRest",
"dojo/store/Memory",
"dgrid/OnDemandGrid"
], function (dom, on, Observable, JsonRest, Memory, OnDemandGrid) {
var store = new JsonRest({
target: 'client/list',
idProperty: 'id'
});
var grid = new OnDemandGrid({
columns: {
"id": "ID",
"number": "Name",
"description": "Description"
},
sort: "lastName",
store: store
}, "grid");
});
client/list is a rest url returning a json object {data:[...]}, but the content of the list never shows up :/
I think the problem is caused by the async data loading, because with a json hard coded object the content show up
EDIT :
I've succeeded in achieving this by using a dojo/request, but the JsonRest shouldn't normally act the same way ? Can someone point me to the right direction ?
require([
'dojo/dom',
'dojo/on',
'dojo/store/Memory',
'dojo/request',
'dgrid/OnDemandGrid'
], function (dom, on, Memory, request, OnDemandGrid) {
request('client/list', {
handleAs: 'json'
}).then(function (response) {
// Once the response is received, build an in-memory store with the data
var store = new Memory({ data: response });
// Create an instance of OnDemandGrid referencing the store
var grid = new OnDemandGrid({
store: store,
sort: 'id', // Initialize sort on id, ascending
columns: {
'id': 'ID',
'number': 'Name',
'description': 'Description'
}
}, 'grid');
console.log(store);
on(dom.byId('queryForm'), 'input', function (event) {
event.preventDefault();
grid.set('query', {
// Pass a RegExp to Memory's SimpleQueryEngine
// Note: this code does not go out of its way to escape
// characters that have special meaning in RegExps
description: new RegExp(this.elements.last.value, 'i')
});
});
on(dom.byId('queryForm'), 'reset', function () {
// Reset the query when the form is reset
grid.set('query', {});
});
});
});
Ok problem found :/
My "client/list" url was returning a json object like this:
{data: [{id:"1", label: "test"}, {id:"2", label: "test"}]}
Turns out that the JsonRest object is already encapsulating data in a data node, so by returning a json like this:
{[{id:"1", label: "test"}, {id:"2", label: "test"}]}
everything worked fine :)

Remote paging grid in extjs

You are my last chance :(. Im trying do work a paging grid with mvc pattern.
The grid show the fisrt 21 records, but not refresh when click "next" pagingtoolbar icon.
All my codes are detailed below:
The Store:
Ext.define('CRUDManantiales.store.grid.AbmUsuarios', {
extend: 'Ext.data.Store',
model: 'CRUDManantiales.model.grid.AbmUsuarios',
proxy: {
type: 'ajax',
url: 'resources/bundles/usuarios/generarJsonTodos.php',
reader: {
type: 'json',
root: 'data',
successProperty: 'success',
totalProperty: 'total'
}
}
});
The main view code:
Ext.define('CRUDManantiales.view.grid.AbmUsuarios', {
// [..........]
initComponent: function () {
this.store = 'grid.AbmUsuarios';
this.dockedItems = [{
xtype: 'pagingtoolbar',
store: this.store,
beforePageText: 'Página',
afterPageText: 'de {0}',
displayMsg: 'Mostrando {0} - {1} de {2} registros',
emptyMsg: 'No hay datos que mostrar',
dock: 'bottom',
displayInfo: true,
pageSize: 21
}];
this.callParent(arguments);
}
});
I wasted four days in this code, appreciate your assistance. Thanks !!
Thanks for all. The problem has been resolute. The fail was that i was using POST array in my PHP script and needed use GET method. :)

Resources