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?