Wednesday, December 14, 2011

Class File PHP

I sent a few hours and came up with a Class file that would represent my counter:

id = $id;

//get recs from db
$rec = $this->getRec();
$totalCount = $this->getCounterTotal();

//update instance vars
$this->counterName = $rec->name;
$this->counterValue = $totalCount;
}

private function getRec(){

$rec = mysql_query("
SELECT id, name
FROM tablename
WHERE id = $this->id
");

return mysql_fetch_object($rec);
}

private function getCounterTotal(){
//select and count recs equal to id
$rec = mysql_query("
SELECT COUNT(id) AS count, date
FROM tablename
WHERE counterid = $this->id AND active
");

$row = mysql_fetch_object($rec);
return $row->count;
}

// accessors
public function getCounterName() {
return $this->counterName;
}

public function getCounterValue() {
return $this->counterValue;
}

//mutators
public function incrementCounter() {

//update db
mysql_query("
INSERT INTO tablename
(counterid)
VALUES
($this->id)
");

//var_dump($this->id);
//break;

}


public function resetCounter(){
//get recs for the counterid
mysql_query("
UPDATE tablename
SET active = 0
WHERE counterid = $this->id
");

//var_dump($this->id);
//break;
}

public function getAllRecs(){
$recs = mysql_query("
SELECT c.name AS name, a.date AS date, a.schoolid AS schoolID, a.active AS active

FROM tablename a
join tablename c on c.id = a.counterid

ORDER BY date DESC
");

return $recs;
}

}

?>

While building my class file, I used a test.php file along with it to test it. A common practice when building bus. classes. Once the class was complete, I completed the DB table.

I ended up creating two tables:

tablename
tablename_associations

The tablename includes an id and a name for the counter.

Most of the data storage is in the associations table, where i am storing the id, the date of the request and a boolean col representing if the col is active in the current count, since it can be reset.

Next, I build an administration page that would allow whoever we gave access to it to reset each of the counters. Also on the admin. page is a report of each of the requested counts: see below






Now came the trickiest part of all. The problem I ran into next, was my new learning of the week. When using AJAX, which is essentially the XMLHTTPRequest object , that you CAN NOT remotely call a page on another server. This is know as the same server policy. This was a big problem since the server that was serving up the counter requests was NOT THE SAME as the server that was hosting the class(s) and db that were storing the counter. I had no way to reconcile this since I did not own the client server, only the serving server.

Hmmmm, what to do next??

This post got me started to what my option would be, which was basically two

1 - create or use a proxy server to fool the client and server into thinking they were the same domain
2 - use a different javascript notation called JSON, that would allow you to inject a script.

Neither of these options seems too trivial, after about a day of reading up on the two, i choose option 2., JSON.

Here is the JSON enabled call from the client side:

function getCounterJSON(param){
$.getJSON('http://domainName/path/view.php?callback=?','counter=' + param ,function(res){
document.getElementById(param).innerHTML = '&nbsp&nbsp&nbsp' + res.counterValue + ' views';
});

}

Here is the view.php page and its callback function.

//VERY sneaky JSON javascript object notation callback function - working around the security *blocks when ajaxing from one domain to another - which is illegal.
{
echo $_GET['callback'] . '(' . "{'counterValue' : $counterValue}" . ')';
}

Here is the rest of the view.php page preceding the callback function.

//CounterBase creates the objects $marks, $attendance, $progress
include_once 'CounterBase.php';

//check to see if someone is requesting to update a specific counter
$counter = $_GET['counter'];
$counterValue = 0;

//var_dump($_GET['counter']);
//break;

if ($counter == 'marks') {
$counterValue = $marks->getCounterValue();
}elseif($counter == 'attendance'){
$counterValue = $attendance->getCounterValue();
}elseif($counter == 'progress'){
$counterValue = $progress->getCounterValue();
}

counters, javascript, JSON and PHP



I have a customer that forwarded me an email that said "can we create Linkcounters on our web page?" My first thought was, its not the 90's, people don't use counters anymore. So I did a little research, about 5 minutes, and found a couple web sites that create counters for you. Like this one and this one. I send a email back with links to these sites and said something like, its pretty easy.

Then I got an email from my boss who said, "James, I think they want you to do it for them". So, I spent about 1/2 hr and documented the steps necessary to create a counter using one of the two sites, mailed the steps to my customer and waited. Here is a copy of my email with the steps:

Ellie, follow these steps for each page you want to insert the counter code on.
go to e-zeeinternet.com site
1 - enter the page URL, like https://siteURL , into the Page Counter that it will be placed on:
2 - choose Numbers of digits to show
3 - Choose pageviews
4 - Choose No, twice
5 - Select the counter style you prefer
6 - scroll to bottom of page, click Get Counter Code
7 - copy the contents from the box
8 - using an html editor, open the page specified in step 1
9 - paste the code into the location where you want counter to appear
10 - save the page
11 - reload the page and you should see the counter
you can edit the code a bit, to remove the text, for example.
I tested out on an html page on this end and works fine.
james

Next, I got an email from a guy down the hall who supports this customer I had just emailed. She emailed her contact, the guy down the hall, when she received this message from me.

Toby, the guy down the hall, said "james, i tried doing something like this before, but i don't know where to put the code. the plot thickens"...

Once I spoke with Toby further, I found out that the customer wants to track the # of times 3 specific links are clicked in their existing system. After clarifying a couple other issues, Toby gave me access to his test server and away I went back to my corner of the world to see about creating counters for the 3 links.

I googled a bit for "creating web counters" and found almost all javascript solutions, many of which used cookies to store information for a user. Cookies was a good solution, at least initially. You can see the alert() in the functions as debugging options. This was enjoyable, tinkering around in javascript until I got the code working.

Javascript Cookies

The basic premise of the cookie is a way for the browser to remember or persist information about the user when they come to a web page. Great, perfect, if the requirement was for user to keep their own counters.

Three requirements I was solving:

1 - adding a call to the incrementCookieCount function when the user clicked on a specific link.
2 - call the getCookieCount function for the 3 links requested, outputting the value of the cookie next to the link.
3 - creating a link that would allow the user to reset the cookie count, when they wanted. This would basically delete the cookie and recreate it, setting its count back to 1.

This was great, all this counting and incrementing and displaying and resetting was just fun, and I was able to do it all right in the client side browser. I was very proud once I got everything working. I showed my customer, he was excited bla bla...

Here is how I was calling the increment function:

if(data_type == 2){
//alert('attendance ' + data_type);
incrementCookieCount('attendance');
}else if(data_type == 3){
incrementCookieCount('marks');
}else if(data_type == 8){
incrementCookieCount('progress');
}


Here is how I was displaying the count:

getCookieCount('progress');


Here are the functions:

function incrementCookieCount(cookieName){
//alert('');
var count = GetCookie(cookieName)
if(count == null) {
SetCookie(cookieName,'1')
return 1
}else{
var newcount = parseInt(count) + 1;
DeleteCookie(cookieName)
SetCookie(cookieName,newcount,exp)
return count
}
}

function getCookieCount(cookieName){
//alert('');
var count = GetCookie(cookieName)
if(count == null) {
SetCookie(cookieName,'1')
return 1
}else{
var newcount = parseInt(count);
DeleteCookie(cookieName)
SetCookie(cookieName,newcount,exp)
return count
}
}


//these are like private functions, not called directly by the client.

function GetCookie (name) {
var arg = name + "=";
var alen = arg.length;
var clen = document.cookie.length;
var i = 0;

while (i < clen) {
var j = i + alen;
if (document.cookie.substring(i, j) == arg)
return getCookieVal (j);
i = document.cookie.indexOf(" ", i) + 1;
if (i == 0) break;
}
return null;
}

function SetCookie (name, value) {
var argv = SetCookie.arguments;
var argc = SetCookie.arguments.length;
var expires = (argc > 2) ? argv[2] : null;
var path = (argc > 3) ? argv[3] : null;
var domain = (argc > 4) ? argv[4] : null;
var secure = (argc > 5) ? argv[5] : false;
document.cookie = name + "=" + escape (value) +
((expires == null) ? "" : ("; expires=" + expires.toGMTString())) +
((path == null) ? "" : ("; path=" + path)) +
((domain == null) ? "" : ("; domain=" + domain)) +
((secure == true) ? "; secure" : "");
}


var expDays = 30;
var exp = new Date();
exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

function DeleteCookie (name) {
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (name);
document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}


function resetCookie(param) {
//alert('resetting cookie... ');
//var name = "marks";
var exp = new Date();
exp.setTime (exp.getTime() - 1);
var cval = GetCookie (param);
document.cookie = param + "=" + cval + "; expires=" + exp.toGMTString();
}


function getCookieVal(offset) {
var endstr = document.cookie.indexOf (";", offset);
if (endstr == -1)
endstr = document.cookie.length;
return unescape(document.cookie.substring(offset, endstr));
}

This is what the web page looked like with my code in place:






This is what the output looked like from the web page.








When I checked the layout in another browser, it hit me, that the solution I had created was not the one being asked for. This solution would give every user in each unique browser their own counters. What I needed was a solution that would persist outside of any browser and user.

I would need a server side solution, and a database that would store the counter information, persist and read/reset. Hmmmmm

I turned toward PHP, since I had a PHP server available and a mySQL database that could store the data.

Step one: Create a class that would represent the counter, using PHP.

Step two: Build a persistence mechanism for the counter data.

Step three: Modify the javascript to read PHP class file(s).

Step four: Use an AJAX technique to call the counter update and increment functions, while outputting their results in the html page. This would be tricky, but I had done similar things using AJAX and Jquery in the past.

Continued in next post.....