Archive for February, 2008

Creating a Google Account

February 14th, 2008 by Bobby Whitman

Google offers an excellent online suite of products, all of which are free to you, the end user. dynamIt often leverages the power of Google when developing sites of our clients. In fact, it is a standard dynamIt practice to install Google Analytics on all site we launch. In addtion, dynamIt often uses Google’s search engine optimization (SEO) tools and encourages it clients to consider GMail as their electronic mail client. In order to fully utilize these web tools, you must have an active Google account.

Signing up for a Google accoutn is a relatively painless process. First, visit the following site.

https://www.google.com/accounts/NewAccount

Step 1: You will be asked to enter the following information: a current e-mail address, a password, and location. In addition, you must confirm your password by simply typing the same password in the box labeled ‘Re-enter password’ and complete a word verification.

After this, breeze through the Google terms of service and when you are ready, click the button labeled ‘I accept. Create my account.’

Step 2: Before you may begin using your google account, you must verify the e-mail address that you entered. You will be automatically sent an e-mail from google after completing the sign-up form. Wait a minute or two and then check this e-mail account.

When you receive this e-mail, open it up. There will be a link in the e-mail that you are instructed to click. Click it.

You should be taken to a Google page telling you that your account has been acitvated. Also, Google has logged you in.

Be sure to remember your username and password for google. Also, let dynamIt know your Google login so that we may give you access to the analytics account we have setup for your site.

Integrating UPS Online Tools with PHP/mySQL e-commerce

February 12th, 2008 by Bobby Whitman

Today, I was faced with a brand new challenge. A client had contracted us to create an online store complete with custom shopping cart and payment gateway interaction. After carefully considering business logistics, the client decided to do all of the shipping of online sales using UPS. So, in order to accurately calculate shipping costs to pass along to the customer we were asked to integrate UPS Online Tools into the checkout process we were designing. The goal was to have the client select their preferred method of shipping, display the cost for UPS to ship to their zip code, and have that cost added to the total so it could be charged to the customer’s credit card.

“No problem,” I thought. Surely, UPS has a great API with tons of resources and sample scripts, right? Well, not so much. All I really got out of them was a 63 page PDF filled mostly with XML 101 and an error code reference. The only sample code I could find was written Java and Visual Basic. After all, who needs samples in popular web languages like ASP, ColdFusion, Perl, and PHP?

Ok, so let’s turn to Google, surely someone has done this before and is willing to share their source with the community, right? Again, no luck. I googled for the better part of an hour finding nothing more than some software piece for sale claiming to do it and a bunch of unanswered forum posts from about 4 years ago.

Looks like I am on my own. So, I rolled up my sleeves and started poking around the UPS service and I have what I think is a good solution. Now, I am writing this resource paper so I can share this solution with all, so the next person looking need go no farther.

Goal: Given a destination city/zip/country, an approximate weight of the package, and the type of shipping service I want to order from UPS (e.g. 2nd day air, ground, etc.) be able to calculate shipping rates on the fly and store that data in my database so I can record it as part of the order.

To achieve this end I will want to use the UPS Rates and Service Selection XML Tool. In order to use this, I will need an account at UPS.com and what is called a Developer’s Key that you can use to generate an XML Access Key.

This tool works as follows:
1. You format a request using XML and the format specified by UPS. This format is explained in the Developer’s Guide provided by UPS.
2. Send this request to the UPS service via HTTP POST.
3. The UPS service will then output a response in XML.

When we get this response from UPS we can parse the resultant XML using PHP and retrieve the data we desire.

Step 1: Create the XML using the correct format for UPS.

Essentially there is two things we must do here. First, we have to gain access to the UPS service. We do this by sending an AccessRequest through XML. In this exmaple, your ‘UserId’ and ‘Password’ make up your UPS.com login and ‘AccessKey’ is the XML Access Key generated through UPS.com.

<?xml version=”1.0″?>
<AccessRequest xml:lang=”en-US”>
<AccessLicenseNumber>AccessKey</AccessLicenseNumber>
<UserId>UserId</UserId>
<Password>Password</Password>
</AccessRequest>

Second, we send data regarding the shipment for which we want costs calculated. We take these two XML files, concatenate them, and send them both in our request.

<?xml version=”1.0″?>
<RatingServiceSelectionRequest xml:lang=”en-US”>
<Request>
<RequestAction>Rate</RequestAction>

<RequestOption>Rate</RequestOption>
</Request>
<Shipment>
<Shipper>
<ShipperNumber>ShipperNumber</ShipperNumber>
<Address>
<City>Columbus</City>

<PostalCode>43220</PostalCode>
<CountryCode>US</CountryCode>
</Address>
</Shipper>
<ShipTo>
<Address>
<City>Cincinnati</City>

<PostalCode>45207</PostalCode>
<CountryCode>US</CountryCode>
</Address>
</ShipTo>
<ShipFrom>
<Address>
<City>Columbus</City>

<PostalCode>43220</PostalCode>
<CountryCode>US</CountryCode>
</Address>
</ShipFrom>
<Service>
<Code>03</Code>
</Service>

<Package>
<PackagingType>
<Code>02</Code>
<Description>Customer Supplied</Description>
</PackagingType>
<Description>Rate</Description>
<PackageWeight>

<UnitOfMeasurement>
<Code>LBS</Code>
</UnitOfMeasurement>
<Weight>10</Weight>
</PackageWeight>
</Package>
</Shipment>
</RatingServiceSelectionRequest>

You can pretty much see what is going on here. But to clarify, we send details about the Request and the Shipment, which involves the following information:

Shipper – UPS assigned ShipperNumber and general info about the shipper.
ShipTo – Critical information (city, zip code, and country) on the shipment destination.
ShipFrom – Critical information (city, zip code, and country) on the shipment source.
Package – Information about the package including packaging type and weight of package.
Service – A code for the UPS service to use. See Below.

<?

$ups_service = array(
’01′ => ‘UPS Next Day Air®’,
’02′ => ‘UPS Second Day Air®’,
’03′ => ‘UPS Ground’,
’12′ => ‘UPS Three-Day Select®’,
’13′ => ‘UPS Next Day Air Saver®’,
’14′ => ‘UPS Next Day Air® Early A.M. SM’,
’59′ => ‘UPS Second Day Air A.M.®’,
’65′ => ‘UPS Saver’,
);

?>

Note that you may choose receive information on the costs of all UPS products for this shipment. In this case we change the RequestOption to ‘Shop’ and omit the ‘Service’ node.

This is the basic structure of the XML, there are a number of additional fields you may specify regarding the Shipment, for more information here, please refer to the Developer’s Guide provided by UPS.

Next, I am going to use some PHP so we can parameterize the critical information:

<?

$destCity = $_POST['x_ship_to_city'];
$destZip = $_POST['x_ship_to_zip'];
$destCountry = ‘US’;

$shipWeight = $_POST['ship_weight'];
$shipType = $_POST['ship_method'];

$shipperNumber = ‘ENTER SHIP NUMBER’;

$myCity = ‘Columbus’;
$myZip = ’43220′;
$myCountry = ‘US’;

$accessLicense = ‘ENTER ACCESS KEY’;
$userId = ‘ENTER USER ID’;
$password = ‘ENTER PASSWORD’;

$XML = ‘<?xml version=”1.0″?>
<AccessRequest xml:lang=”en-US”>
<AccessLicenseNumber>’ . $accessLicense . ‘</AccessLicenseNumber>
<UserId>’ . $userId . ‘</UserId>
<Password>’ . $password . ‘</Password>
</AccessRequest>
<?xml version=”1.0″?>
<RatingServiceSelectionRequest xml:lang=”en-US”>
<Request>
<RequestAction>Rate</RequestAction>
<RequestOption>Rate</RequestOption>
</Request>
<Shipment>
<Shipper>
<ShipperNumber>’ . $shipperNumber . ‘</ShipperNumber>
<Address>
<City>’ . $myCity . ‘</City>
<PostalCode>’ . $myZip . ‘</PostalCode>
<CountryCode>’ . $myCountry . ‘</CountryCode>
</Address>
</Shipper>
<ShipTo>
<Address>
<City>’ . $destCity . ‘</City>
<PostalCode>’ . $destZip . ‘</PostalCode>
<CountryCode>’ . $destCountry . ‘</CountryCode>
</Address>
</ShipTo>
<ShipFrom>
<Address>
<City>’ . $myCity . ‘</City>
<PostalCode>’ . $myZip . ‘</PostalCode>
<CountryCode>’ . $myCountry . ‘</CountryCode>
</Address>
</ShipFrom>
<Service>
<Code>’ . $shipType . ‘</Code>
</Service>
<Package>
<PackagingType>
<Code>02</Code>
<Description>Customer Supplied</Description>
</PackagingType>
<Description>Rate</Description>
<PackageWeight>
<UnitOfMeasurement>
<Code>LBS</Code>
</UnitOfMeasurement>
<Weight>’ . $shipWeight . ‘</Weight>
</PackageWeight>
</Package>
</Shipment>
</RatingServiceSelectionRequest>’;

?>

Step 2: Post the XML to UPS.

Now that we have generated a properly formatted request we need to send this to the UPS service for real-time processing. To do so, we will uses PHP built-in CURL functions. If you are not familiar with CURL, get more here: http://curl.haxx.se/, or here: http://us2.php.net/manual/en/ref.curl.php. The following code connects to the UPS server, POSTS the XML data, and returns the HTTP output to the $resp variable. As a result, $resp is now a string containing the XML that UPS has sent back. If you request was successful, this XML contains the shipping cost data that we want.

<?

$ch = curl_init(“https://wwwcie.ups.com/ups.app/xml/Rate”);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $XML);

$resp = curl_exec($ch);

curl_close ($ch);

?>

Step 3: Parsing the response XML with PHP.

Finally, we have the correct response from the UPS server. We need to parse this XML data to get what we want into our database or at the very least a PHP variable so we can add it to the total of the shipment. For this I will use the SimpleXML class that is built into PHP 5+.

<?

$data = new SimpleXMLElement($resp);

?>

This will load all the XML data conveniently into a PHP object. Drop in a and you will see exactly what we have to work with. We can then hack through the XML structure fairly easily to get what we want, or use XPath to essentially query our XML.

<?

$cost = (double)$data->RatedShipment->TotalCharges->MonetaryValue;

?>

The variable $cost now has the shipping price that we need to charge our online customer. You can now use this data in your existing e-commerce application.

Lastly, suppose you wish to display all UPS shipping services with their associated prices so that your customer could make a choice based on price. As I mentioned above you can change the RequestOption node in your request XML to have a value of ‘Shop’. If this modification is made, the UPS XML response includes multiple RatedShipment nodes, one for each service. If this is the case, we can use the snippet below to build an array where our keys are the UPS shipping service codes and the values are the associated costs.

<?

$shipping = array();
foreach($data->RatedShipment as $rate) {

$service = (string)$rate->Service->Code;
$cost = (double)$rate->TotalCharges->MonetaryValue;

$shipping[$service] = $cost;

}

?>

Visibility: not really hidden;

February 12th, 2008 by Bobby Whitman

I came across an interesting CSS problem with the visibility property today. It seems that when you set an element to visibility: hidden you run into a couple unpleasant bugs in Firefox.

1. Where is my cursor?

Let’s say we have an HTML form and we are going to open up a dialog <div> with JavaScript to display instructions to the user. This dialog has an ‘Ok’ button which, when clicked, will set the dialog <div> to have a visibility of hidden so that the user can return there attention to filling out the form.

The problem: This dialog <div> although hidden, is still in between the user and the form and as a result it is covering up the users cursor. The result is a form with input boxes that you click in but never know where you are typing because you cursor is mysteriously missing.

2. The Mac Power PC problem.

Our CMS was recently inflicted with this bug. In a way is shows its face in Firefox for any platform, but it is particularly detrimental to your site when the end-user is on a Power PC Mac (Mac built with an Intel chip does not have this same problem). Again, the scenario calls for some div on top of content that has had its visibility set to hidden.

The problem: As you scroll down the page the box tends to make the content stick for a second before righting itself. Although it may be annoying, this is not really a problem as you can see the outline of the hidden div for just an instant and then it is corrected. However, if you are browsing the web from a Power PC Mac (I am not sure why you would want to be, but, hypothetically, let’s say you are) then when scrolling the content sticks and it does NOT correct itself. The result it this large patched of frozen content from higher up on the page covering the content that you should be looking at.

The solution is simple. DO NOT USE VISIBILITY: HIDDEN TO REMOVE YOUR DIV. If you read up on your CSS you learn that that setting an element’s visibility to hidden leaves that element right where it is but makes it invisible. The important fact is that the element has not moved, it is still on top of the content you want seen. There should be no problem here at all, if it is completely invisible then who cares if it still there? Well such is a bug, should not cause problems, yet it does.

Instead, use the CSS display property. To hide the element set display to none. This will actually remove the element from your document and not display it at all. For more information on the display property, click here: http://www.w3.org/TR/CSS21/visuren.html#display-prop.

Setting Rules with JavaScript

February 12th, 2008 by Bobby Whitman

dynamIt often runs into the following problem with users of our CMS: Organization X
has a website that provides information to its members. On this website they frequently
link to other sites on the internet . They need some way to display a disclaimer and warn
their users that they are leaving the official web site of Organization X and traveling
to a foreign site. The person using the CMS is likely not the most tech savvy person
and therefore does not understand how to add simple JavaScript to their link to display
this disclaimer.

The solution: do what we call “setting rules” with JavaScript.

First, consider to which HTML elements this rule will apply. In our example
this is easy, it will apply to all links or tags. jQuery makes it simple to
retrieve all of these elements

$(“a”)

Thanks to jQuery we can make our search for tags even more specific. jQuery allows
us to test attributes of the element. In this example we want to find all
tags in
which the href attribute starts with ‘http://’.

$(“a[href^='http://']“)

Now that we have found all such links in the page, we need a way to loop through them.
JavaScript has the standard loop structures, however jQuery make this even easier. After
we have selected the right links with jQuery we can loop through using the jQuery
each() function. The each() takes one parameter, that is a function which will
be executed in the context of each element.

$(“a[href^='http://']“).each(function() {

});

Inside this function we refer to the current iteration’s link element as $(this).
We now use jQuery to manipulate the link and warn the user that they our leaving our site.
Also, we need all of this JavaScript to happen automatically, again jQuery comes in
handy here with the ready event.

$(document).ready(function() {

$(“a[href^='http://']“).each(function() {

var myhref = $(this).attr(‘href’);

$(this).attr(‘href’, ‘#’).attr(‘link’, myhref).click(function() {
if(confirm(‘Warning this link will take you to another site.<br />Are you sure you wish to leave?’)) {
location.href = $(this).attr(‘link’);
}
});
});
});

You see will here, that when the user now clicks on the link it will run JavaScript’s built-in
confirm command that will popup a system dialog asking the user to continue.
If the end-user clicks ‘Ok’, the confirm will return true and it will redirect
the user to the location of the original link. For more information on the JavaScript
confirm box, click here:
http://www.w3schools.com/js/js_popup.asp.

dynamIt on jQuery

February 10th, 2008 by Bobby Whitman

JavaScript is a rather complex language, lot of ins, lot of outs, lot of what-have-yous. It is important to gain a good understanding of the language so that you can understand what is open to you in the world of client-side scripting. However, writing some advanced scripts can be very tedious and time consuming.

There are many advantages to using a JavaScript framework. To name a few:

  • It is easier to use, code is written more quickly.
  • Advanced JavaScript tactics are simplified
  • Code is likely more efficient
  • Great community support

The next step is selecting the right framework. There are many JavaScript frameworks out there. You may have read about jQuery, Prototype, Scriptaculous, Dojo, MooTools, Adobe Spry, etc, all are quite popular.

dynamIt prefers jQuery, mostly because we tried it and we liked. We are not saying that jQuery is any better than the others, simply in and of itself jQuery rocks. jQuery has great documentation and is really easy to pickup and use. It’s also really flexible and simplifies many JavaScript tasks.

Throughout our resources we will often speak in terms of jQuery.

To find out more: http://www.jquery.com.