www.webdeveloper.com
Results 1 to 12 of 12

Thread: My First Script, how does it look?

  1. #1
    Join Date
    Oct 2013
    Posts
    25

    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: https://github.com/peezybro/trackUser

    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();
    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

  2. #2
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,506
    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.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  3. #3
    Join Date
    Oct 2013
    Posts
    25
    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!

  4. #4
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,506
    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.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  5. #5
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,506
    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;
    	}
    }
    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.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  6. #6
    Join Date
    Oct 2013
    Posts
    25
    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);
    };
    Thanks for the help once again

    I really do enjoy writing javascript, and hopefully be able to find a better job here soon!!!

  7. #7
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,506
    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)
    }
    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.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  8. #8
    Join Date
    Oct 2013
    Posts
    4
    You can view and analyze your json object. at http://codebeautify.org/view/json

  9. #9
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,506
    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.
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

  10. #10
    Join Date
    Oct 2013
    Posts
    25
    Thanks, It helps a lot!

  11. #11
    Join Date
    Oct 2013
    Posts
    4
    Quote Originally Posted by \\.\ View Post
    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.
    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.

  12. #12
    Join Date
    Mar 2007
    Location
    localhost
    Posts
    2,506
    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)
    }
    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;
    	}
    }
    Yes, I know I'm about as subtle as being hit by a bus..(\\.\ Aug08)
    Yep... I say it like I see it, even if it is like a baseball bat in the nutz... (\\.\ Aug08)
    I want to leave this world the same way I came into it, Screaming, Incontinent & No memory!
    I laughed that hard I burst my colostomy bag... (\\.\ May03)
    Life for some is like a car accident... Mine is like a motorway pile up...

    Problems with Vista? :: Getting Cryptic wid it. :: The 'C' word! :: Whois?

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles