Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track AJAX site search using Google Analytics?

I'm using AJAX (POST method) for my site search. Here's my AJAX call:

$.ajax({
    url: 'ajax.php',
    type: 'POST',
    dataType: 'json',
    data: {
        search_phrase: search_phrase
    },
    success: function(data) { ...

My aim is to use Google Analytics to start tracking search terms. Any idea how this can be done?

like image 398
henrywright Avatar asked May 13 '15 12:05

henrywright


2 Answers

In your success callback lodge a virtual pageview with Google Analytics. Overwrite the page page for that pageview to include a query parameter (unlike KayKay's answer I'm assuming Universal Analytics):

success: function(data) { 
  ga('send', 'pageview', 'search.php?q=mykeyword');
  .........

(there is not enough info about yor page code to see how to retrieve the keyword - either read it with jQuery from your search input field, or you can extract it from the ajax request).

This will count every search as a pageview, but since searching replaces the content that makes sense IMO.

Set up internal site search in your views to work with (in my example) the "q" parameter (and click "remove search parameter from url").

If you do not want to touch your ajax function you can use global ajax event handlers from jQuery, but that's a bit harder to set up.

like image 169
Eike Pierstorff Avatar answered Oct 19 '22 01:10

Eike Pierstorff


You can trigger a google analytics event when sendind the ajax call. This is done as shown in the documentation using :

_gaq.push(['_trackEvent', 'YourAjaxCallName', 'The posted value as a string']);
like image 36
kgautron Avatar answered Oct 19 '22 00:10

kgautron