/    Sign up×
Community /Pin to ProfileBookmark

My First Script, how does it look?

I am currently learning Javascript, PHP, and OPP. I decided to create a simple script for my company I work for. trackUser logs unique users who visit the website. It keeps track of; screen resolution, screen viewport, browser + version, operating system, date visited, and IP Address.

github: [url]https://github.com/peezybro/trackUser[/url]

Here is the code I wrote for the script.

[CODE]var trackUser = {
init: function(){
this.resolution = this.detectResolution();
this.viewPort = this.detectView();
this.browser = BrowserDetect.browser + ” ” + BrowserDetect.version;
this.OS = BrowserDetect.OS;
if (this.detectCookie() == false){
this.setCookie();
this.ajaxCall();
} else {
console.log(‘User is not unique, kill trackUser’); //debug
return;
};
},
detectResolution: function(){
var width = window.screen.width,
height = window.screen.height,
res = width + “x” + height;
console.log(‘detecting resolution’); //debug
return res;
},
detectView: function(){
var width = window.screen.availWidth,
height = window.screen.availHeight,
view = width + “x” + height;
console.log(‘detecting viewport’); //debug
return view;
},
detectCookie: function(){
var check = $.cookie(‘uniqueUser’);
if (check == null) {
console.log(‘cookie is not set’); //debug
return false; //cookie is not set
} else {
console.log(‘cookie is set’); //debug
return true; //cookie is set
};
},
setCookie: function(){
$.cookie(‘uniqueUser’,’set’, { expires: 1 });
console.log(‘setting cookie’); //debug
},
ajaxCall: function(){
console.log(‘called ajaxCall function’); //debug
$.ajax({
type: “POST”,
url: “saveData.php”,
data: {
resolution: this.resolution,
viewport: this.viewPort,
browser: this.browser,
os: this.OS
},
success: function(){
console.log(‘success’); //debug
return;
},
error: function(){
console.log(‘Ajax had a error while sending data to server, Please check code.’);
}
});
}
};
trackUser.init();[/CODE]

I wrote this as a learning project so I am sure there is properly problems with my code. Please let me know how i did, and any tips will help ?

to post a comment
JavaScript

11 Comments(s)

Copy linkTweet thisAlerts:
@rootOct 25.2013 — Less reliance on JQuery and I would say nice job.

As for the relevance to this forum, this really isn't a show and tell, its a help forum for coding problems ?

If you have problems with your code, please state what the problem is that you are experiencing.
Copy linkTweet thisAlerts:
@peezyauthorOct 25.2013 — Thanks, I ended up removing all jquery from it and focusing on vanilla JS.

Plain JS is a big wake up call for me, so I am sure I will be back with lots of questions!
Copy linkTweet thisAlerts:
@rootOct 25.2013 — Plain JS is not that hard to learn.

If you search for what you want to learn, eg, cookies then you can find function that set, retrieve and delete them.

AJAX is also a well covered subject with many examples.
Copy linkTweet thisAlerts:
@rootOct 25.2013 — Within your above example script, your screen detection could be rewritten as its own JSON object.

[CODE]screenSize = {
properties:{
available:{height:window.screen.availHeight,width:window.screen.availWidth},
view:{height:window.screen.height,width:window.screen.width}
},
resolution: function(){
with(screenSize.properties.available)
return height+"x"+width;
},
view: function(){
with(screenSize.properties.view)
return height+"x"+width;
}
}[/CODE]


This then gives the user two routes to obtaining the desired information, directly

scrHt = screenSize.properties.view.height;

scrWd = screenSize.properties.view.width;

or a string giving the details of both

sizes = screenSize.view();

As you will begin to appreciate, design is also a factor in writing JavaScript code.
Copy linkTweet thisAlerts:
@peezyauthorOct 25.2013 — Thanks for the information! I ended up using the JSON Object for the screenSize like you suggested. One question I do have about it though, why and where to use a JSON Object? I read around and understand JSON is a smaller and simpler XML, but I can't understand when to use it. Or in other words what is the main difference between a JSON Object and a regular JavaScript Object?

For the Ajax, I ended up creating my own callAjax function to handle my Ajax calls.

[CODE]function callAjax(args) {
var type = args.type,
url = args.url,
data = args.data,
xmlhttp,
define = function() { //defines the ajax request
try {
// Opera 8.0+, Firefox, Safari, chrome
xmlhttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
},
handle = function(){ //handles the ajax call
if(xmlhttp.readyState == 4){
if(xmlhttp.status == 200){
var response = xmlhttp.responseText;
console.log(response);
} else {
console.log('Their was an error with the Ajax call'); //debug
}
}
},
convertString = function(obj){ //converts query string to object
var str = '';
for(key in obj){
str += key + '=' + obj[key] + '&';
}
str = str.slice(0, str.length - 1);
return str;
},
convertQuery = function(str){ //converts object to query string
var obj = {},
arr = str.split('&');
for(var i=0; i < arr.length; i++){
var bits = arr[i].split('=');
obj[bits[0]] = bits[1];
}
return obj;
};
define();
parameters = convertString(data);
xmlhttp.open(type, url, true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.onreadystatechange = handle;
xmlhttp.send(parameters);
};
[/CODE]


Thanks for the help once again ?

I really do enjoy writing javascript, and hopefully be able to find a better job here soon!!!
Copy linkTweet thisAlerts:
@rootOct 26.2013 — JSON is an acronym for JavaScript Object Notation, it is more Object based and there is no hard and fast answer when is best to use it.

If you have a number of functions that are related to a larger function, then it might serve better as a JSON object.

I will generally write an automatic function that needs to be executed when a page is loaded in this sort of fashion.

[CODE]json = {
failure:0,
clock:function(){
var now = new Date().toTimeString().slice(0,9);
json.theDOMtarget.innerHTML = now;
},
init:function(){
if( json.theDOMtarget=document.getElementById("idOfDOMelement") ){
clearInterval(json.auto);

json.auto = setInterval("json.clock()",1000);
}else if( ++json.failure > 10 ) clearInterval(json.auto);
},
auto:setInterval("json.init()",1000)
}[/CODE]


if after 10 seconds the clock target is not available, the callback is stopped.

The example layout groups a number of functions that all work together for a specific purpose, this is handy because when things work, you can discount them from debugging code problems, a working json function that is not reliant on any external functions won't suddenly develop a bug, so they have advantages.

The only draw back to a JSON object is that it has to fully initalize before any part of it can be used, so auto:setInterval("json.init()",1000) has to have its function call in quotes otherwise ti wouldn't properly initialize and the function would have an error in it.
Copy linkTweet thisAlerts:
@james_malviOct 26.2013 — You can view and analyze your json object. at http://codebeautify.org/view/json
Copy linkTweet thisAlerts:
@rootOct 26.2013 — Utter rubbish James, having just tried it, the thing fails on line 1 on an object that is functioning perfectly fine, no errors and is pretty as it already is.
Copy linkTweet thisAlerts:
@peezyauthorOct 28.2013 — Thanks, It helps a lot!
Copy linkTweet thisAlerts:
@james_malviOct 29.2013 — Utter rubbish James, having just tried it, the thing fails on line 1 on an object that is functioning perfectly fine, no errors and is pretty as it already is.[/QUOTE]

Try this one

http://jsonviewer.codebeautify.org/ I have fixed the code.. Let me know if you are getting error and if possible steps to follow. that will really help to improve this product.
Copy linkTweet thisAlerts:
@rootOct 30.2013 — Error: Parse error on line 1:

json = {

failur

^

Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

Tried it on: [CODE]json = {
failure:0,
clock:function(){
var now = new Date().toTimeString().slice(0,9);
json.theDOMtarget.innerHTML = now;
},
init:function(){
if( json.theDOMtarget=document.getElementById("idOfDOMelement") ){
clearInterval(json.auto);

json.auto = setInterval("json.clock()",1000);
}else if( ++json.failure > 10 ) clearInterval(json.auto);
},
auto:setInterval("json.init()",1000)
}[/CODE]


and got:

Error: Parse error on line 1:

screenSize = {

^

Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '[', got 'undefined'

from : [CODE]screenSize = {
properties:{
available:{height:window.screen.availHeight,width:window.screen.availWidth},
view:{height:window.screen.height,width:window.screen.width}
},
resolution: function(){
with(screenSize.properties.available)
return height+"x"+width;
},
view: function(){
with(screenSize.properties.view)
return height+"x"+width;
}
}[/CODE]
×

Success!

Help @peezy spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...