Converting PHP Call Tracking Script to JavaScript

Hello!

My first post on SitePoint, and many thanks to anyone who can help me out here, whether it be direct code, or even a point in the right direction!

My problem: I need to convert a server-side PHP call tracking script into client-side JavaScript so that it will function in any language (ASP, .NET, HTML, etc.) I will post the finished PHP script below and do my best to comment each section clearly, but please don’t hesitate to ask if anything is unclear.

The functionality: The basic function of this script is to display different phone numbers on a website, depending on how the user enters the site. For example, if a user enters the site from a search engine, 111-111-1111 will be displayed, but if the user enters from direct URL entry, 333-333-3333 will be displayed. There are a few basic scenarios that will need to be met, which I will list here:

  1. If a specified query is in the URL, display number 000-000-0000.
  2. If the user comes from a search engine and the client name is in the query string, display number 111-111-1111.
  3. If the user comes from a search engine and the client name is NOT in the query string, display number 222-222-2222.
  4. Otherwise, display number 333-333-3333.

I have a pretty good understanding of PHP and was able to create the script below from scratch, with help of course from W3Schools, PHP.net, and various other awesome tutorials throughout the 'net. I also have a lot of experience with ActionScript, which seems to have a lot in common with JS, but this is my first attempt at JS and I am still trying to wrap my head around most of it.

If any of you JavaScript experts out there could help me out with converting some of the functions (strstr, parse_url, etc.), and any other best practices, I would be so grateful!

I will be continuing to work hard on this all week, and will update this thread with my progress.

Thank you all in advance for your help!


<?php

/* Parse the referring url and, if it is one of the search engines
listed, return the specified name. */
function GetReferringHost() {
	$refer = parse_url($_SERVER['HTTP_REFERER']);
	$host = $refer['host'];

	if (strstr($host,"google")) {
		return "Google";
	} elseif (strstr($host,"yahoo")) {
		return "Yahoo";
	} elseif (strstr($host,"bing")) {
		return "Bing";
	} elseif (strstr($host,"aol")) {
		return "AOL";
	} elseif (strstr($host,"ask")) {
		return "Ask";
	} elseif (strstr($host,"altavista")) {
		return "AltaVista";
	}
}

/* Parse the referring url query string and, if specified
ClientName keyword is present, return "ClientName". */
function CheckQueryString() {
	$refer = parse_url($_SERVER['HTTP_REFERER']);
	$query = $refer['query'];

	if (strstr($query,"clientname")) {
		return "ClientName";
	}
}

/* Check if the referring host is a search engine (called
"natural" here) and if so, return "Natural". */
if (isset($_SERVER['HTTP_REFERER'])) {
	$refHost = GetReferringHost();
	if ($refHost == "Google" || "Yahoo" || "Bing" || "AOL" || "Ask" || "AltaVista") {
		$refHost = "Natural";
	}
	$refKey = CheckQueryString();
}

/* If the query string contains a direct referral, return
number 0, if the referring host is "Natural" (i.e., a search
engine) and "ClientName" is NOT present, return number 1,
if the "ClientName" IS present, return number 2, and
otherwise return number 3. */
if ($ref == "DirectReferralSite.com") {
	$num = "000-000-0000";
} elseif ($refHost == "Natural" && $refKey <> "ClientName") {
	$num = "111-111-1111";
} elseif ($refKey == "ClientName") {
	$num = "222-222-2222";
} else {
	$num = "333-333-3333";
}

/* Check for a cookie or set a cookie for the phone number. */
if (isset($_COOKIE['user'])) {
	$num = $_COOKIE['user'];
} else {
	$expire = time()+60*60*24*30*6; // 6 months
	setcookie("user",$num,$expire);
}
?>

The intention of this seems a bit odd, and this “function in any language” also seems a bit mysterious. Bear in mind that if JS is turned off, it won’t work. People do turn it off! If you can do it on the server side, it’s almost always a better idea than doing it in JavaScript.

Since you seem like a reasonable chap eager to learn, I’d recomment heading over to the MDC and checking out the string functions. There you’ll find some things that look familiar to PHP functions.

For URL parsing, you need the window.location object, which comes with some helpful breakdowns of the entire URI. You can then apply the string functions to the URI.

You’ll also need to check out the documentation on cookies - I’d recommend quirksmode’s tutorial for this.

The rest is pretty much the same: since both languages are part of the C family, they are pretty similar.

Give it a go and then we can point any mistakes.

Raffles,

Thank you very much for your response and encouragement. First off, I completely agree with you regarding the server-side preference. I would much rather utilize server-side whenever possible, which is why I sought to create this script in PHP in the first place. The PHP is perfect for any client site already in PHP (most are), but I was hit with a roadblock after needing this on an ASP site. Also something else was brought to my attention: what about HTML or HTM extensions where no server side is possible? (Although, in my research I’ve been seeing things about server-side JavaScript and client-side PHP??? Still confusing to me, but I will have to look into that more later!)

So, after my initial creation of the PHP, I was then requested to create a JavaScript version that would work on any client site – I had to hit myself for not thinking of creating it in JS from the start! (Would have saved a lot of time to create one script that works everywhere.) Although, even though I couldn’t find any proof anywhere, something inside me knew that server-side was just better and more dependable. So again, I have to thank you for the server-side advice. It confirmed what I was thinking from the start, but with my lack of experience and proof, I couldn’t really stand by my convictions.

And now, onto the code: It works! I made some huge advancements this weekend, building on what I knew about window.location, document.referrer, and RegExp. You’re right; excluding those few PHP functions, the rest was basically the same. Thanks goodness these 2 languages share the C family roots. I can safely say I now love JavaScript as much as PHP! I made a few small logic changes, which I think are good improvements over the PHP script anyway, and learned a lot from the Quirksmode cookies tutorial – thanks for that too!

I tested it thoroughly, but there could still be some glaring issues; if you have some time to look through it, I would be very appreciative.

Let me know! Thanks again!


function GetReferringHost() {
	var refer = document.referrer;
	var parts = refer.split("/");
	var host = parts[2];	
	
	if (host == "www.google.com") {
		return "Google";
	} else if (host == "search.yahoo.com") {
		return "Yahoo";
	} else if (host == "www.bing.com") {
		return "Bing";
	} else if (host == "aolsearcht10.search.aol.com") {
		return "AOL";
	} else if (host == "www.ask.com") {
		return "Ask";
	} else if (host == "www.altavista.com") {
		return "AltaVista";
	} else {
		return null;
	}
}
function CheckQueryString(term) {
	var refer = document.referrer;
	var parts = refer.split("?");
	var query = parts[1];
	
	var regex = new RegExp(term);
	var isBrand = regex.test(query);
	if (isBrand == true) {
		return term;
	} else {
		return null;
	}
}
function CreateCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function ReadCookie(name) {
	var nameEQ = name+"=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function EraseCookie(name) {
	createCookie(name,"",-1);
}

// get natural referrer and check query string
var refHost = GetReferringHost();
if (refHost == "Google" || refHost == "Yahoo" || refHost == "Bing" || refHost == "AOL" || refHost == "Ask" || refHost == "AltaVista") {
	var isNatural = true;
}
var refKey = CheckQueryString("clientname");

// set number
if (isNatural == true && refKey != "clientname") {
	var num = "NumberNatural";
} else if (isNatural == true && refKey == "clientname") {
	var num = "NumberBrand";
} else {
	var num = "NumberNormal";
}

// check for cookie or set cookie
var c = ReadCookie("num");
if (c) {
	num = c;
} else {
	CreateCookie("num",num,210); // 6 months
}

Well, if it works, it works. Looks OK to me.

If a webpage has a .html extension that does not mean there is no server-side language that has spat it out! It is very common for some webservers to be set up so that .html files are parsed for PHP as well, for instance. It can also be set up so that any language can be used to produce the output HTML, and some fictitious .html file is used as the “identifier” for what the user is requesting. mod_rewrite is another example where URIs can be manipulated so that the user sees a certain URI, but the logic for outputting that HTML is somewhere completely different.

There is no such thing as client-side PHP. Server-side JavaScript exists but is uncommon.

I’m glad it led to you learning some JavaScript. :slight_smile: