2

I am figuring out of i can make something like Google analytics script. They work with javascript to capture data and send it to an given URL. But i want it to do without ajax or REST API.

What i found so far:

<script type="text/javascript">
var statsPage = 'http://www.uw-url.be/process.php';
var stats = {
    page: location.href,
    browser: 'ie',
    ip: '127.0.0.1',
    referral: 'google.com?search=test'
};
var params = $.param(stats);
alert(statsPage+'?'+params);
</script>

The alert message gives everything i need, but the problem is how can i send those data to statsPage URL? I found a little solution around the web for that but i don't know of it is ok... Maybe there is a better solution to do this, but i don't know... I'm listening to you guys!

$('<img>', {
    src: statsPage + '?' + params
}).appendTo('body').remove()

There is something else... If i look to the analytics javascript code this is a total other script. Can anyone explain me how it works?

An example here:

<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-49578310-1', 'auto');
  ga('send', 'pageview');

</script>

The meaning of the whole thing here is that everyone can use this on their website. With AJAX or REST API it is not possible to integrate it simply. Not anyone can work with that.

For my first posted script i make also use of jquery () for that. Analytics script don't.

EDIT

I have build a new code based on the answer from Peter G. I don't need jquery for that. Is this code safe enough to use? I have written a function for the p var:

function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}

ca("pageview", "1", "male");

The whole script below:

<script type="text/javascript">
var statsPage = 'http://www.my-url.com/response.php';

function ca(c,o,n,t,e,t,u){return p={type:c,userid:o,gender:n}}

ca("pageview", "1", "male");


var params = Object.keys(p).map(function(k) {
    return encodeURIComponent(k) + '=' + encodeURIComponent(p[k])
}).join('&')

const req = new XMLHttpRequest();
//req.addEventListener('load' /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();

req.onreadystatechange = function() {
    if (req.readyState == XMLHttpRequest.DONE) {
        alert(req.responseText);
    }
}
</script>

Like you can see, i have hidden the addEventListener here. What is the difference to use this with or without that?

Brecht27
  • 85
  • 1
  • 1
  • 8

1 Answers1

6

Some inspection of the code used by Google Analytics (use an unminifier like http://unminify.com/ ...the code is far too long to reproduce here) shows that most of the code is related to determining WHAT to send, rather than how to send it. Here's the interesting part about how they send it:

// ...
    wd = function(a, b, c) {
        var d = O.XMLHttpRequest;
        if (!d) return !1;
        var e = new d;
        if (!("withCredentials" in e)) return !1;
        e.open("POST", a, !0);
        e.withCredentials = !0;
        e.setRequestHeader("Content-Type", "text/plain");
        e.onreadystatechange = function() {
            4 == e.readyState && (c(), e = null)
        };
        e.send(b);
        return !0
    },
    x = function(a, b, c) {
        return O.navigator.sendBeacon ? O.navigator.sendBeacon(a, b) ? (c(), !0) : !1 : !1
    },
// ...

O is the window object. They perform an XMLHTTPRequest when the page is loaded and they use the navigator.sendBeacon function when the page is closed. If all you want to do is send your data over the internet, I'd suggest the XMLHTTPRequest method, as navigator.sendBeacon is intended to send data on page close (so the page doesn't lag when closed, you'll see no difference on page load). If all you want to do is send the data as a GET request, you can do the following (although, you should consider refactoring so you can use a POST request instead...).

const req = new XMLHttpRequest();
req.addEventListener('load', /*callback after req is complete*/);
req.open('GET', statsPage + '?' + params);
req.send();

Note that you don't actually need the addEventListener callback if you don't care about the result of the call. Read more about XMLHttpRequest() here.

You might also run into CORS issues if the URL you're requesting is different from the one you're on and you use the addEventHandler callbacks. Read more on that on this SO page seeing as it's out of the scope of this question.

Community
  • 1
  • 1
Peter G
  • 2,773
  • 3
  • 25
  • 35
  • Also just a heads up since you seem to be new here, if this helped you don't forget to click the green checkmark to accept it. You'll get some points (2) for doing so. – Peter G Oct 28 '16 at 00:51
  • If i use your last code with const req in the beginning, i think i have to use jquery.param for serializing the params? Or is it possible to get/post the params array without jquery? – Brecht27 Oct 28 '16 at 11:54
  • You can serialize the parameters without jQuery. The serialization is just getting them into URL format like "example.com/page.html?param1=value1&param2=value2" (the part after the '?' is URL formatted). Use encodeURIComponent(string) to get this formatting. – Peter G Oct 29 '16 at 06:21
  • Can you look closer on my last post below here? Give me your opinion please! And maybe answer my questions there. – Brecht27 Oct 29 '16 at 08:39
  • Anyone else who can help me here? – Brecht27 Oct 31 '16 at 12:33
  • 1
    Sorry, took me a while to get back to this. Your `params` string isn't correct I don't think. I tested it with {lol: 5, la:1} and got 'lol=undefined&la=undefined'. Another thing to be careful of is that in `function ca(c,o,n,t,e,t,u)` the second `t` won't do anything. If you use `addEventListener` it will fire a callback letting you know if the request returns successfully or not. You probably don't need this for analytics. – Peter G Nov 02 '16 at 10:56
  • 1
    Also in the future if you have more questions, the right thing to do is to post another question (assuming it wouldn't be a duplicate). This also helps you get more visibility. – Peter G Nov 02 '16 at 10:58
  • yes i see that the in the ca function the second t won't do anything because i had a t before in the function. My params are working correct with this code. I have tested myself and it is ok. I don't use addEventListener but for the return i use the onreadystatechange with function. They give me the response in alertbox from the response.php callback page. – Brecht27 Nov 02 '16 at 20:59
  • The second part of the script is posted here: http://stackoverflow.com/questions/40318060/detect-browser-tab-close-without-jquery-and-send-some-data-to-php-file I need to know also when the page is closed (or browser tab) so i can calculate the timeSpend on the page. Maybe you can look at this to give your opinion here? – Brecht27 Nov 02 '16 at 21:01