Teach The Net
Home of the Seanybob
  • Home
  • About Me
  • Links
  • My Portfolio
  • My Programs
  • USURP

Archive for September, 2009

Designer Fu

-Programming/Coding, CSS, Design, HTML No Comments »

There’s always been a kind of divide (at least in my mind) between designers and developers – developers tend to be great at programming, designers tend to be good at graphics and website panache – with little common ground between the two.  As a result, many developers will work with a designer at their side, but differences in their levels of understanding about what can and cannot be done with code in the browser can often introduce problems.  Thus, it is necessary for designers to know a certain amount of code, and for developers to know enough about design to be able to make suitable corrections to site designs that are otherwise impossible to do within the realm of HTML, CSS, and Javascript.

The same thing is also true if a developer is working in an environment where they don’t have anybody available to do design – at some point with whatever is being developed, some design decision is going to have to be made.

A lot of my work in the past year has involved a certain element of design, something that has never been my forté.  One of the things that I have found helpful to overcome this is to constantly be looking at what other people are doing, design-wise.  These are two resources I have found extremely helpful.

Smashing Magazine is a website dedicated to giving case studies of the latest trends in design, partially with a focus on graphic design for websites.  For example, in the recent past I’ve seen articles on trends in design for footers, navigation, iconography, and 404 pages.  They basically go out and find all of these great examples of what can be done within the limitations of HTML, CSS, and Javascript.  Having so many examples of excellent design available can help when it comes time to create something on your own (and don’t you dare plagiarize…).

A List Apart focuses on a wide variety of design-related issues, ranging from using CSS to create page layouts, to design trends, usability, SEO and more.  A lot of people are fans of the CSS articles in particular because using CSS to create a page’s layout is a difficult but rewarding way of doing things – it’s a lot harder and less cross-browser-compatible to create a drop-down menu using Javascript instead of CSS (although CSS is not without cross-browser differences).


September 24th, 2009 |



Useful Javascript References

-Programming/Coding, Javascript No Comments »

For a while, I’ve been using Patrick Hunlock’s references to help me out when I forget how to do something in Javascript, or else what the arguments of a certain Javascript function are. They’ve proved very useful.

  • The Complete Javascript Numbers Reference
  • The Complete Javascript Strings Reference
  • The Complete Javascript Dates Reference
  • Mastering Javascript Arrays
  • Mastering JSON – JSON is an extremely useful tool for storing any Javascript data – objects, arrays, strings, numbers, etc. – in a standardized string format. The data that is converted to a JSON string can then be imported into other Javascript code or other programming languages (PHP 5.2.0+ includes native support for JSON with json_encode and json_decode) and translated to those languages’ versions of objects, arrays, strings, numbers, etc.  See json.org for more JSONy goodness.
  • Functional Javascript – an excellent tutorial on Javascript functions and the multitude of ways they can be used

I need to make a shirt that says “I <3 Hunlock”.  Lord knows he’s saved my tail more than once. ;)


September 23rd, 2009 |



Javascript Countdown and DB Update with jQuery and AJAX

-Programming/Coding, Javascript, Php No Comments »

Here’s another way of doing Sean’s Javascript countdown and DB update script using jQuery’s AJAX functionality instead of updating an iframe.  I would favor this approach for two reasons:

  1. The <iframe> tag is deprecated in the W3C HTML 4.01 Strict, XHTML 1.0, and HTML 5 standards.  However, it will still work (probably just for legacy support), although HTML 5 only supports the src attribute (see W3Schools’s iframe reference for more).
  2. As noted, this way uses jQuery.  jQuery is useful for a number of reasons.  First, it completely frees you from worrying about browser incompatibilities – if you use jQuery’s methods, all jQuery functionality is guaranteed to work in IE 6.0+, Firefox 2.0+, Safari 3.0+, Opera 9.0+, and Chrome.  Second, it provides a standardized and much simpler syntax for interacting with the browser DOM.  Third, using jQuery greatly condenses the amount of code you have to write for certain tasks (maybe I’ll write a post about that someday with some examples).  Fourth, and most relevant to this post, jQuery greatly simplifies the process of making AJAX calls to run server-side scripts.

So, let’s get started.

The Problem
We need a script that will:

  1. Force the user to view an ad, page, etc. (hereafter: ‘content’) for a certain period of time.
  2. When the user has finished viewing the content, update your own database to keep track of what the user has viewed.
  3. Anddddd do this all without iframes.

The Solution

<html>
<head>
<title>Your Site</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var x = 30; // put your number of seconds here

function advanceClock() {
    x--;
    $("#clock").text(x + " seconds left");

    if( x <= 0 ) {
        $.ajax({
            url: "http://www.your-site.com/done.php",
            type: "GET",
            data: "ad=794&ver=2c2de84d375855003a53f3a9f",
            dataType: "text",
            success: function(r) {
                clearInterval(timer);
                $("#clock").html(r);
            }
        });
    }
}

$(document).ready(function() {
    timer = setInterval("advanceClock()", 1000);
});
</script>
</head>

<body>

<div id="clock"></div>
<!-- Your content here //-->
</body>
</html>

Now we need to do some explaining.

$("#clock").text(x + " seconds left");

Sean did the update of the screen’s text a bit different than this. His code looked like this:

document.frm.clock.value = x

One of the very neat things about jQuery and other Javascript frameworks such as MooTools is that they have a tool called the dollar-sign selector. Basically, you can do a dollar-sign, followed by parentheses (just like a function). Anything in quotes (with a few exceptions; I’ll note one later with document) within the parentheses is interpreted as a CSS3 selector (although the jQuery team has extended this a lot; see the jQuery selector documentation for more).

Just as with CSS, “#clock” will refer to the item that has its id attribute set to “clock”, which in this case is our <div> tag in the <body> tag. After the dollar-sign selector can come a jQuery function (examples: .text(), .html(), .append()) to apply to the DOM elements retrieved by that selector (another neat feature: they can be chained together – example: $(“div a”).html(“<div>some html</div>>).append(“some more stuff”)).

In this case, we are using the .text() function, which sets the text inside of the items found using the dollar-sign selector to whatever text you pass the .text() function. So every time our advanceClock() function runs, it will update the clock div to display the text “x seconds remaining”. If you had multiple divs displaying the time, you could also use the dollar-sign selector to update all of them at once, like this:

$("div .aDivClassName").text(x + " second remaining");

All of the divs with their class attribute set to “aDivClassName” would be updated at once. Spiffy, ay?

        $.ajax({
            url: "http://www.your-site.com/done.php",
            type: "GET",
            data: "ad=794&ver=2c2de84d375855003a53f3a9f",
            dataType: "text",
            success: function(r) {
                clearInterval(timer);
                $("#clock").html(r);
            }
        });

This code makes the AJAX call to the server that we only need to do once. Sean’s solution was to update the iframe on his page so that its content was whatever done.php fed out. Using his same done.php script with this method, we use AJAX to call that server side script and get the result. Note that we’re using the dollar-sign selector here, too. It’s very powerful. “$.” by itself refers to the entire jQuery object, so you can call any of the jQuery functions without actually using the selector (the part in parentheses). The data we need to make the AJAX call is given to the .ajax() function in the form of one argument. Weird syntax to you? Using {} in Javascript code makes what is known as an object literal – that is, you’re defining an object on the spot. All you need to know to use this for the moment is that the form an object literal takes is:

{
    variableOneName: "variableOneValue",
    variableTwoValue: 2,
    varThreeValue: varDeclaredOutsideOfObject
}

Note that the value for each property in the object (variables in an object are called properties) can be any type of data – strings, numbers, other objects, arrays, variables declared outside of the object literal, functions, etc.

So when we pass the object literal to .ajax(), it basically expects to find predefined variable names (url, data, dataType, success). Here are the variables we’re using for our AJAX call:

  • url – this is the url that we need to get. It needs to be a string.
  • type – This is the type that we should make. It can be either “GET” or “POST”. Use according to what your PHP script expects.
  • data – This is the data that you need to pass as variables to your script. We use it exactly like we would use if we were calling done.php using Sean’s script – take a look at his URL: “done.php?ad=794&ver=2c2de84d375855003a53f3a9f470b3e6″. The data variable in our .ajax() call is the portion after the “?” in Sean’s URL.
  • dataType – This tells the .ajax() function what type of data we expect to get back. You can read the jQuery .ajax() options documentation for more information on this. For our purposes, we just want to get the straight text that the done.php script outputs.
  • success – This argument should be a function, which we are declaring without the function name (you can do that if you’re setting a variable’s value to a brand new function – then you just refer to the function by the variable name). In this case, we are passing it a function that clears the interval we will set (see below for more on setInterval()) and then updates the #clock div’s HTML. Why did we put the clearInterval() function here? Well, we don’t want the interval to be cleared if the AJAX call failed, because if the call failed then the user’s information won’t get updated. Thus, if the AJAX call fails, the interval gets called again and the script has another shot at updating the user’s information. That’s also why when we test for x’s value, we ask for <= 0, because x might be 0 or less than 0, and in both cases we should try to make the AJAX call.
  • One last piece of information in the script:

    $(document).ready(function() {
        timer = setInterval("advanceClock()", 1000);
    });

    Remember how I said that in some cases the dollar-sign selector’s argument doesn’t have to be a string? This is one of those exceptions. Since “document” refers to the actual DOM item, jQuery can work with this and use it directly – although I’m pretty sure “document” as a string would work too.

    Now, what this piece of code does with the .ready() function is wait and make sure that the DOM has been fully loaded. Imagine this: the user is connecting with an ancient 14.4kbps internet connection, maybe because they’re in some remote, rural area where they don’t have the benefit of Verizon’s insanely fast FIOS service. If the script gets loaded and processed by the browser before the #clock div has been loaded and made available in the DOM, it won’t get updated with the value. What $(document).ready() does is wait for the DOM to be fully loaded, thus preventing such issues. .ready() accepts one argument, a function, again passed like we did with the success variable in our AJAX call. This function will be executed when, and only when, the DOM is ready. All we do inside of this function is set our interval, which calls the advanceClock() function every 1000 milliseconds (one second).

    Now, a little word on why I used setInterval() in set of setTimeout(): it avoids an extra bit of code and can just be cleared when we are done. With setTimeout(), we have to setTimeout() again at the end of every call of Sean’s startClock() function because setTimeout() is a one-time deal – it only calls the code given to it one time. setInterval(), on the other hand, will be called continuously until we clear the interval.

    And there you have it: A fully functional (don’t blame me if there are some bugs, I didn’t actually test this script ;) – but then again, that’s what great debuggers like Firebug are for) clock countdown and database update script that uses jQuery AJAX calls instead of the deprecated iframe tag.


    September 23rd, 2009 |



News from Australia/NZ

Funny Stuff, Random (personal) No Comments »

Over the past year, I’ve always kept an eye open for news from Australia and New Zealand. There are two reasons for this. The first is simply that I love both those countries, and long to visit them again. The second… is that their news is absolutely unique.

Here’s a collection of news stories I’ve gotten over the past year.

Penguin deaths prompt sniper aid
Professional snipers have been brought in to guard a vulnerable colony of penguins in Australia.

‘Naked police run’ investigated
Australian police are investigating whether officers ran naked round an unmarked police van as they travelled to a stag party.

Aussie straps in beer, not child
A car driver in Australia has been fined for strapping down his beer rather than his young child.

Man arrested over barter mishap
A New Zealand man who tried to barter marijuana for snacks overlooked one important problem – a policeman was standing right behind him.

Cattle farms lure Australia women
A record number of young Australian women are signing up for jobs as cattle hands on vast outback farms. (Jillaroos??? Hahaha)

NZ judge orders ‘odd’ name change
A judge in New Zealand made a young girl a ward of court so that she could change the name she hated – Talula Does The Hula From Hawaii.

Australian plea for ‘ugly’ women
The mayor of a remote Australian mining town has come under fire after saying that female “ugly ducklings” might benefit from its shortage of women.

Australia suffering ‘man drought’
An analysis of new census figures has shown that Australia is suffering from an unprecedented “man drought”.

Large pushy pig traps Australian
A woman on the north coast of New South Wales in Australia is being held hostage in her own home by a large pig, Australian media report.

Driver lost on 600km shops trip
An 81-year-old Australian man became lost on an early morning drive to the shops and ended up almost 600km (370 miles) away from his starting point.

Clinton jokes about ‘former’ PM Clark
Clinton calls the current prime minister of New Zealand the ‘former PM’. Helen Clark (the PM) totally pwns Clinton in her response.

And lastly…


September 23rd, 2009 |



Account Creation Re-enabled.

Random (Other) No Comments »

Just informed that I’d (somehow) turned off new user account registration. This has been re-enabled — you can now create an account to post comments if you want to :D


September 23rd, 2009 |



Apologize

Roll Towards Me (Band) No Comments »

The band’s first release!
Piano: RJ Lynn
Guitar: Michael Burke
Vocal: Lisa Vanni
Recording/Spiffy-er: Sean Kooyman

Download Link

One Republic: Apologize

I’m holding on your rope,
Got me ten feet off the ground
I’m hearin what you say but I just can’t make a sound
You tell me that you need me
Then you go and cut me down, but wait
You tell me that you’re sorry
Didn’t think I’d turn around, and say…

It’s too late to apologize, it’s too late
I said it’s too late to apologize, it’s too late

I’d take another chance, take a fall
Take a shot for you
And I need you like a heart needs a beat
But it’s nothin new
I loved you with a fire red-
Now it’s turning blue, and you say…
“Sorry” like the angel heaven let me think was you
But I’m afraid…

It’s too late to apologize, it’s too late
I said it’s too late to apologize, it’s too late

It’s too late to apologize, it’s too late
I said it’s too late to apologize, it’s too late
It’s too late to apologize, yeah
I said it’s too late to apologize, yeah-
I’m holdin on your rope, got me ten feet off the ground…


September 23rd, 2009 |



Audio File Converter

Programs I Use No Comments »

The best I’ve found. Converts most major filetypes, is completely free, and the resulting file sounds just fine (not horribly corrupt, like some other file converters I’ve used).

Name: Switch Sound File Converter

http://nch.com.au/switch/index.html

My Mirror


September 23rd, 2009 |



Creating a countdown with javascript that will update a database

-Programming/Coding, Javascript, Php 1 Comment »

This is a lot more complicated that it sounds… or is it?

Javascript works client-side; therefore, whatever occurs in the javascript cannot interact with the server. Php/mysql is server side, and so needs to have all it’s functions/commands done BEFORE you start doing javascript.

There is a solution… I used this for the countdowns on Adverbux. It works perfectly.

First, Here is the page with the countdown on it:

Code:
<html>
<HEAD>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="-1">
<body bgcolor=white>
<TITLE>Your Site</TITLE>

<script>
var x = 30
var y = 1
function startClock(){
if(x!==”Done”){
x = x-y
document.frm.clock.value = x
setTimeout(“startClock()”, 1000)
}
if(x==0){
x=”Done”;
document.frm.clock.value = x
success.location.href=”done.php?ad=794&ver=2c2de84d375855003a53f3a9f470b3e6″;

}
}
</script>

</HEAD>
<body leftmargin=”0″ rightmargin=”0″ topmargin=”0″ bottommargin=”0″ onLoad=”startClock()” >

<form name=”frm”>

<INPUT TYPE=”TEXT” NAME=”clock” SIZE=”3″ readonly style=”border: none; padding: 0; font-size: 25pt; font-weight: bold; font-family: Verdana; BACKGROUND-COLOR: #FFFFFF; vertical-align:top;”>

<iframe name=”success” src=”empty.html” frameborder=”0″ border=”0″ framspacing=”0″ marginheight=”0″ marginwidth=”0″ scrolling=”no” vspace=”0″ hspace=”0″ width=”40″ height=”40″></iframe>
</form>

</body>
</html>

I’ll work through this step by step with you. First look at the javascript in the above code example. See this?
var x = 30
var y = 1

The x value (in this case 30) is how many seconds you want the time to countdown. So once the page fully loads, the javascript will be executed, and the timer will start counting down from 30.
The function startClock works as-is – it checks to see if the timer has reached 0 yet.

Now for the next important item. You will notice two lines in the script above. The first…
success.location.href=”done.php?var1=blah&var2=777&var3=ilikecheese”;

The second…
<iframe name=”success” src=”empty.html” frameborder=”0″ border=”0″ framspacing=”0″ marginheight=”0″ marginwidth=”0″ scrolling=”no” vspace=”0″ hspace=”0″ width=”40″ height=”40″></iframe>

The first part (success.location.href) is what the iframe success is sent to after the timer reaches 0. The second part is what the iframe is initially set to.

On adverbux, we have a file called empty.html. It’s… empty. So it just shows as white space on a white background. Once the timer completes itself, this small, 40 x 40 iframe is redirected to the done.php page, which processes the variables transferred in the URL via the GET method. The done.php page then checks to see if the user passes several tests to make sure their view is valid – if it is, it prints out a dollar sign, which appears in the iframe success – if it’s not, it prints out a red circle with a line through it in the same spot.

A sample done.php page…

Code:
<?php
if($_GET['var1']=='blah' && $_GET['var3']=='ilikecheese')
{
mysql_query("UPDATE people SET ads={$_GET['var2']}");
print"(thumbs up)";
}
else
{
die("Improper use of this page.")
}
?>

Some things to keep in mind… the space for the iframe (currently set to 40 pixels by 40 pixels) is easily adjusted. It’s important to encrypt the variables in the url that you are using in the javascript, as users can easily exploit them. What we do on adverbux is take some specific strings that are different for every ad, and add them to a static string, then md5 it. We then do the same thing on the done.php page and make sure they are the same hash.
For example…
$var=md5($ad.”Seanybobrox”);

That’s about it… You can understand most of it just looking at the code above. Any questions let me know.

(*Note – there probably is some way to do with this ajax as well, but I didn’t bother spending the time to figure that out)


September 21st, 2009 |



Creating a Random Statement content area

-Programming/Coding, Php No Comments »
Create a file called
randomthought.php

PHP Code:
<?php
// change this to location of your text file
$xfile = "randomthoughts.txt";
$xline = file($xfile);
$xline = str_replace("\n","",$xline);
$xline = str_replace("\r","",$xline);
srand((double)microtime()*1000000);
echo
$xline[rand(0,count($xline))]."<br />";
?>

Create a file called
randomthoughts.txt
Fill this with your own sayings, or use mine (see attached)

Now to randomly display one of these “thoughts” on a page, add this code

PHP Code:
<? include_once('randomthought.php'); ?>
http://teachthe.net/files/randomthoughts.txt


September 21st, 2009 |



Creating a User Stats image

-Programming/Coding, Php No Comments »

For this tutorial, I will be focusing on PNG images. This method is possible for JPGs, and I think GIFs as well, but a couple functions would need to be changed.

Ok, first things first. You need a starting image. I would suggest taking mine and editing it.
[Image: sig.png]
Here is what the finished product looks like
[Image: 1.png]

When we’re done, you will have this set up so it updates everytime your user logs in.

Ok. Create a file called sig.php
sig.php

Code:
<?php

//connect to your mysql database here

//this will be the user’s ID number
$value=abs((int)$_GET['v']);

$query = ‘SELECT username,user_level,totmoney,signedup,totads,totref,donatordays FROM users WHERE userid = ‘.$value;
$e = $db->query($query);
$x = $db->fetch_row($e);
$query2 = ‘SELECT totmoney FROM users WHERE totmoney>’.$x['totmoney'];
$en = $db->query($query2);
$rank = $db->num_rows($en);
$rank+=1;
$x['totref']=number_format($x['totmoney'],2);
$x['totref']=” $”.$x['totref'];
$x['totads']=number_format($x['totads']);

// Check cache
$cache = ‘psigs/’.$value.’.png’;
if (file_exists($cache))
{
$delold=unlink($cache);
}

// Load image thing
$im = imagecreatefrompng(‘images/sig.png’);
$font = ‘fonts/franklin.ttf’;
$color = imagecolorallocate($im, 188, 222, 255); // Blueish or so
// Write
imagettftext($im, 12, 0, 112, 31, $color, $font, $x['username']);
// COlumn one
// Y: 40 X: 28
// Need new lines
$leftfy = 50;
$gap = 10;
if($x['user_level']==0){$x['user_level']=’Member’;}
if($x['user_level']==1){$x['user_level']=’Member’;}
if($x['user_level']==1 && $x['donatordays']>0){$x['user_level']=’Upgraded’;}
if($x['user_level']==2){$x['user_level']=’Admin’;}
if($x['user_level']==3){$x['user_level']=’Staff’;}
imagettftext($im, 9, 0, 80, $leftfy, $color, $font, $x['user_level']);
imagettftext($im, 9, 0, 80, $leftfy + 1 + $gap, $color, $font, $rank);
imagettftext($im, 9, 0, 80, $leftfy + 3 + ($gap * 2), $color, $font, $x['totref']);

// Column 2
imagettftext($im, 9, 0, 200, $leftfy, $color, $font, $x['totads']);

// Signup thing
$days_old = time() – $x['signedup'];
$days_old /= 86400;
$hrs_left = $days_old – floor($days_old);
$hrs_left = 24 * $hrs_left;
$hrs_left = floor($hrs_left);
imagettftext($im, 9, 0, 200, $leftfy + 1 + $gap, $color, $font, floor($days_old).’ days’);
if (strtotime($x['laston']) > strtotime(‘-15 minutes’)) {
$oc = imagecolorallocate($im, 0, 200, 0);
$of = ”;
} else {
$oc = imagecolorallocate($im, 220, 0, 0);
$of = ”;
}
imagettftext($im, 9, 0, 200, $leftfy + $gap * 2, $oc, $font, $of);
header(‘Content-Type: image/png’);
imagepng($im, ‘psigs/’.$value.’.png’);
header(“Location: loggedin.php”);
?>

Edit the above file to put your mysql database connection info at the top of the file, and changing any variables as you see fit. Also you may want to change the final line of code from loggedin.php to any other page you’d like (read below for more info on that).

Now for the tough part. You need to setup this file so it works in between your login page and your page that shows after you login. For the purposes of this tutorial, we will show them as follows:

Login page = login.php
Page after login = loggedin.php

(It’s necessary to keep in mind that some sites have an interim page, and the process of login works like this: Login page, authetication page, page after login. In this case, put this code in between the authetication page and the page after login)

On the login page (or authetication page), after correctly verifying the user’s input, get the user’s ID number from the database, and add this code right after it.

Code:
header("Location: sig.php?v=USERIDOFMEMBER");

I’d be happy to help you troubleshoot any problems you come into


September 21st, 2009 |



Previous Entries
  • You are currently browsing the Teach The Net blog archives for September, 2009.

  • Categories

    • -Personal (135)
      • My Comics (23)
      • Programs I Use (2)
      • Quotations (85)
        • Assorted (17)
        • Bible (11)
        • C. S. Lewis (44)
        • Douglas Wilson (8)
        • George MacDonald (4)
      • Random (personal) (9)
      • Reflections (21)
    • -Programming/Coding (75)
      • AutoIt v3 (3)
      • c++ (4)
      • Call of duty (3)
      • CSS (3)
      • Design (1)
      • HTML (3)
      • Javascript (6)
      • LISP (1)
      • My Programs (31)
      • Php (20)
      • Regular Expressions (1)
      • Robotics (9)
      • Security (1)
      • Visual Basic (24)
    • CSUSB (15)
      • HUM 319 – Myths (7)
      • Mus 180 (8)
    • Other (29)
      • Easter Eggs (4)
      • Funny Stuff (8)
      • Hacks/Tricks (13)
      • Random (Other) (4)
      • Roll Towards Me (Band) (1)
    • USURP (3)
  • Archives

    • July 2010
    • June 2010
    • May 2010
    • April 2010
    • March 2010
    • February 2010
    • January 2010
    • November 2009
    • October 2009
    • September 2009
    • August 2009
    • June 2009
    • May 2009
    • April 2009
    • March 2009
    • February 2009
    • January 2009
    • December 2008
    • November 2008
    • October 2008
  • Recent Posts

    • Random Post: Sb Encrypter
    • Women were not an afterthought.
    • The Cutting Edge
    • Micah 7:18-19
    • Micah 6:8
    • Selected quotes from “A Grief Observed”
    • A very good bed
    • God is good; He is not evil.
    • Merely blank paper
    • Two types of faith.
    • Relative and Absolute will

Copyright © 2010 Teach The Net All Rights Reserved
RSS XHTML CSS Log in
Wp Theme by n Graphic Design
Powered by Wordpress