Google Analytics eCommerce Tracking

Here is the script that needs to be added to the receipt or confirmation page, after the user has completed the sale. You will just need to add php inside of the script so that the content can be created dynamically per customer. One tip is to use a PHP loop. Here is the code:

<script type="text/javascript">



ξ var _gaq = _gaq || [];

ξ _gaq.push(['_setAccount', 'UA-XXXXX-X']);

ξ _gaq.push(['_trackPageview']);

ξ _gaq.push(['_addTrans',

ξ ξ '1234', ξ ξ ξ ξ ξ // order ID - required

ξ ξ 'Acme Clothing', ξ// affiliation or store name

ξ ξ '11.99', ξ ξ ξ ξ ξ// total - required

ξ ξ '1.29', ξ ξ ξ ξ ξ // tax

ξ ξ '5', ξ ξ ξ ξ ξ ξ ξ// shipping

ξ ξ 'San Jose', ξ ξ ξ // city

ξ ξ 'California', ξ ξ // state or province

ξ ξ 'USA' ξ ξ ξ ξ ξ ξ // country

ξ ]);



ξ ξ// add item might be called for every item in the shopping cart

ξ ξ// where your ecommerce engine loops through each item in the cart and

ξ ξ// prints out _addItem for each

ξ _gaq.push(['_addItem',

ξ ξ '1234', ξ ξ ξ ξ ξ // order ID - required

ξ ξ 'DD44', ξ ξ ξ ξ ξ // SKU/code - required

ξ ξ 'T-Shirt', ξ ξ ξ ξ// product name

ξ ξ 'Green Medium', ξ // category or variation

ξ ξ '11.99', ξ ξ ξ ξ ξ// unit price - required

ξ ξ '1' ξ ξ ξ ξ ξ ξ ξ // quantity - required

ξ ]);

ξ _gaq.push(['_trackTrans']); //submits transaction to the Analytics servers



ξ (function() {

ξ ξ var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;

ξ ξ ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';

ξ ξ var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

ξ })();



</script>

Basic AJAX connection using the POST method to retrieve content

Hello guys,

I have been working on a project for school which used AJAX and I just wanted you guys to have this code for reference. This code basically makes a call to a PHP script which gets Zip Code information (city and state) and then adds them into your web page. I used a span tag with id of ???zipinfo??? to act as a holder for the content that was going to be retrieved. Hopefully this helps some of you in your projects.

//Get Zip Code Information

function zipInfo(zipcode) {

fieldValue = ???connection=zipInfo&zip=???+zipcode;

var url=???includes/management.php???;

httpRequest(???POST???, url, true, fieldValue, function(result){

document.getElementById(???zipInfo???).innerHTML = result;

});

}

//AJAX Request

function httpRequest(reqType, url, asynch, fieldValue, callback) {

request = new XMLHttpRequest();

request.open(reqType,url,asynch);

request.setRequestHeader(???Content-type???, ???application/x-www-form-urlencoded???);

request.setRequestHeader(???Content-length???, fieldValue.length);

request.setRequestHeader(???Connection???, ???close???);

request.send(fieldValue);

request.onreadystatechange = function() {//Call a function when the state changes.

if(request.readyState == 4 && request.status == 200) {

callback(request.responseText);

}

}

}

Image Resizing with PHP

Hello guys,

Today I will post a image resizing script, this will assist you in all of your sites specially ecommerce ones in which you need to display your products with different sizes. The script is self explanatory, but please send me a message or a comment if you need further assistance with it.

//Image Target

$pic = ???images/???.$_GET[‘pic’];

//Set Max Sizes

$max_height = 48;

$max_width = 48;

//Get Image Size

$size= getimagesize($pic);

//Set Ratios

$width_ratioξ = ($size[0] / $max_width);

$height_ratio = ($size[1] / $max_height);

if($width_ratio >=$height_ratio)

{

$ratio = $width_ratio;

}

else

{

$ratio = $height_ratio;

}

//Set new size

$new_widthξξξ = ($size[0] / $ratio);

$new_heightξξ = ($size[1] / $ratio);

//Set header

header(???Content-Type: image/jpeg???);

//Create Image

$src_img = imagecreatefromjpeg($pic);

$thumb = imagecreatetruecolor($new_width,$new_height);

imagecopyresampled($thumb, $src_img, 0,0,0,0,$new_width,$new_height,$size[0],$size[1]);

imagejpeg($thumb);

imagedestroy($src_img);

imagedestroy($thumb);

All you need to do now is to point the src element of your image tag to this script, and set the file you desire using the get method. Ex: img.php?pic=image.jpg

Please contact me with any doubts,

GilbertoξCortez

Interactive Web Development for ???The Cloud???

Upload Files From a Form

Hello guys,ξ I decided to do a post on how to upload files from a simple HTML form into your server. First, you will need to set up this form with the proper headings, please see code below.

<form enctype=”multipart/form-data” action=”uploads.php” method=”POST”>

Choose a file to upload: <input name=”uploadedfile” type=”file” /><br />

<input type=”submit” value=”Upload File” /> (Max Size is 2MB)

</form>

As you can see, there is a note stating that the maximum size can be of 2MB’s, you can change this in your php.ini file. Now, you will need to create your uploads.php file, which will receive the file and move it to your desired destination.

//File Upload

$target_path = “uploads/”; //Target Folder

$target_path = $target_path .$timestamp.’_’.basename( $_FILES[‘uploadedfile’][‘name’]);ξ //Final File Destination and name

if(move_uploaded_file($_FILES[‘uploadedfile’][‘tmp_name’], $target_path)) {

echo “The file “.basename( $_FILES[‘uploadedfile’][‘name’]).

” has been uploaded”;

} else{

echo “There was an error uploading the file, please try again!”; //If an error

}

As you can see, I have commented on the code so that it’s more clear to you, feel free to change the address to your desired location. And like always, please feel free to leave any comments, sugestions or questions below.

Thank You,

Gilberto Cortez

Basic Content Management System

If you are a Web Developer like me, then you are always working from different locations, different machines, etc. You do not want to go and look for that client information every time to gain access via FTP to do a small change. There is where a good content management system comes in place. What this is going to allow you to do is to give you the ability to edit any file from any location and from any machine as the editor will be sitting right on the server.

Here is a copy of my Content Management System, which you can just drop in any folder and edit or delete any file in it.

Download My Content Management System

Once you download it, just unzip it and try it in one of your folders. This is a basic management system all that you need to do to install it is to upload, there are a PHP file that is the one doing all the work, and the Tiny MCE folder, which contains all of the required files for the text editor skin, you can delete this if desired. You can also get an updated version by doing a Google search of Tiny MCE.

Please give me your comments and suggestions,

Gilberto Cortez

———————————-

Got termites? Fumigations are the only primaryξrecommendationξgiven by the state. Any other solutions are only secondary and temporary.

Using Loops to Check for Empty Fields

I???ve been noticing lately how many student are creating multiple functions or if statements to do something that is possible in just a couple of lines, in this post I will try to explain how to use Arrays and Loops to validate a form, checking that it does not have any empty fields.

First you need to set up your form, here is the code for a simple log in form:

<form method="post" name="myform" action="login.php">

Username: <input type="text" id="username" name="username"/><br />

Password: <input type="password" id="pass" name="pass"/><br />

<input type="button" value="Log Me In" onClick="validate();"/>

</form>

You might have noticed that at the end of the form, instead of using ???submit??? for the type I used ???button??? instead. I do this to be 100% sure that the form will not be submitted unless it passes the JavaScript Validation. Please be aware that this method will bring a User Experience problem if he or she has JavaScript disabled, for this post please disregard the issue.

After you create your form, then we need to dive into the JavaScript code:

<script type="text/javascript" language="javascript">

function validate(){

//Create Fields Array

var fields = new Array;

var fields = [document.getElementById('username'),document.getElementById('pass')];

//Create Variable to Keep Track of Errors

var err = 0;



//Start Validation Loop

for (i=0;i<fields.length;i++){

//Check Fields in Array to Make Sure they are not Empty

if (fields[i].value == ""){

err++;

}

}//Close Loop

//Check That There are No Errors

if (err === 0){

//Submit Form

document.myform.submit();

}else {

//If there are errors, return false and alert the user

alert("Please Fill Out All Of The Fields");

return false;

}

}

</script>

So there it is guys, all you have to do now is to add more fields to the fields array and it will loop around all of them to check them for empty spaces.

Here is a little more explanation on the script. The first thing that I did is to store my variables, I used an array for the fields being that they have a similar job in common and it will be easire to check them all like this. (An array is created when you have multiple objects with similar properties. For example you could make an array of Car Makes, Car Types, Regular Customers. This is more efficient than creating a different variable for each single item, now you just have to work with one.

After this we start the validation, this is done by looping trough that array to check that the fields are not empty. Let me explain how to create the loop, which is using the for statement. The first line will define where your loop starts, and how many time it will be runned.

Code:

for (i=0;i<fields.length;i++)

Explanation:

for(variable that will be keeping track of how many loops have passed ; how many times will the loop run (the .length property only gives out the array size, so that we can run it that many times ; and finally this step will add one to the loop variable for the next run)

Every time the loop runs, the code between the brackets it???s what is run multiple time. In this case we did an if statement to check the field value. if it finds an empty field it will add one to theξerr variable. After the loop is completed,ξ then we do anotherξif statement to check that there are no errors, if they are none then the form is submitted, is there is an error then it will alert the user and return false.

Hope this helped you out, please leave any comments or suggestions below.

Gilberto Cortez

www.GilbertoCortez.com // Interactive Solutions and Web Development

Send Form Contents to E-Mail

I took the time to do this post because I see a lot of students looking everywhere for a PHP E-Mail script, so here it is:

//Created byξGilbertoξCortez http://www.gilbertocortez.com

//Variables

$form = ???Contact Us???;//Form Name

//Inputs From Form

$name = $_POST[‘name’];

$email = $_POST[’email’];

$phone = $_POST[‘phone’];

$city = $_POST[‘city’];

$comments = $_POST[‘comments’];

//E-Mail Headers

$headers = ???From:???.$email. ???\r\n???;//From E-Mail Header

$headers .= ???Cc:ξdebugg@email.com??? . ???\r\n???;//Debugging E-Mail

$to = ???your@email.com???;//To Address

$subject = ???Message From ???.$form.??? Form???;//Subject Line

//Actual E-Mail Message

$message = ???You received a message from the form named: \???”.$form.???\???:

From: ???.$name.???

E-Mail: ???.$email.???

Phone #: ???.$phone.???

City: ???.$city.???

Comments: ???.$comments.???

???;

//Send E-Mail

mail($to,$subject,$message,$headers);

//Page Re-Direct

header (???Location: thankyou.html???);

Hope you like the script, I added notes to it for easier understanding. Just customize the variables up on top from the fields of your form and for your information. Also remember to add or remove them on the message itself if you change the number or name of the variables.

Any questions or comments are appreciated.

MySQL Database Interaction PHP Class

There are many ways out there to connect to a database, but there is only a few of them that are effective. This is the MySQL object that I use to connect to a database via PHP. You will find this class to be simple but very effective as it’s not overfilled, but it only contains what it’s needed in order to compile a successful application. I have used it multiple times in tasks that include from basic user managements to custom cloud application development. From connecting to a single database, to multiple databases.

Here is the code, please make sure to replace the values of the variables so that you can successfully connect to your database.

class db
{
//Object Variables Please Replace, you can also have them set on the constructor so that you can connect to multiple databases.
private $status;
private $host = ‘localhost’;
private $database = ‘db_name’;
private $username = ‘username’;
private $password = ‘password’;
public ξ$result;
public ξ$results;
function __construct(){
//Connect To Database
$this->status = mysql_connect($this->host,$this->username,$this->password) or die (‘Cannot Open Conection to ‘ .
$this->host);
//Select Database
mysql_select_db($this->database,$this->status);
}
function query($sql){
//Get Results
$this->result = ξmysql_query($sql);
}
function fetch($sql,$type){
//Perform Query
$this->query($sql);
switch ($type){
//Fetch as an Array
case ‘array’:
$this->results = mysql_fetch_array($this->result);
break;
//Fetch as an Asspciative Array
case ‘assoc’:
$this->results = mysql_fetch_assoc($this->result);
break;
//Fetch as an Object
case ‘object’:
$this->results = mysql_fetch_object($this->result);
break;
}
//Return Results
return $this->results;
}
function checkit($sql){
//Check Table for Query
return mysql_num_rows(mysql_query($sql));
}
function __destruct(){
//Free Query Result
mysql_free_result($this->result);
//Close DB Connection
mysql_close($this->status);
}
}

Please let any comments, suggestions orξrecommendationsξon the area below.

Display your last Tweet from Twitter.com

Are you a big Twitter user, and would like to integrate your account into your site? Here is the code to display your last Tweet using the .xml file that is provided by Twitter.

There is only one thing that needs to be changed out. which is the XML file address, you need to input your Twitter ID #. You can get this from clicking on the RSS feed at the bottom of your Twitter Main Page, and extracting this from the URL.

<?php
//Put XML Contents Into Array (PHP.net Function)
function xml2assoc($xml) {
$tree = null;
while($xml->read())
switch ($xml->nodeType) {
case XMLReader::END_ELEMENT: return $tree;
case XMLReader::ELEMENT:
$node = array(‘tag’ => $xml->name, ‘value’ => $xml->isEmptyElement ? ” : xml2assoc($xml));
if($xml->hasAttributes)
while($xml->moveToNextAttribute())
$node[‘attributes’][$xml->name] = $xml->value;
$tree[] = $node;
break;
case XMLReader::TEXT:
case XMLReader::CDATA:
$tree .= $xml->value;
}
return $tree;
}
//Open XML Reading Object
$xml = new XMLReader();
//Open XML File (Replace {id} with your Twitter ID)
$xml->open(‘http://twitter.com/statuses/user_timeline/{id}.xml’);
//Put Document in Arrays
$assoc = xml2assoc($xml);
//Close XML Object
$xml->close();
//Store Result
$lastTweet = $assoc[0][‘value’][0][‘value’][2][‘value’];
//Print Result
echo $lastTweet;
?>
Hope this helps you in your web development. As always, please feel free to leave any comments or suggestions.