August 2009 Archives

Loading a file with AJAX

| No Comments

This is a really neat tutorial that I enjoy using because it uses AJAX. Basically I want to call data into a web site, but I hate having to reload a new page every time for that. What we are going to do is store some data in a separate text file then call that data from our HTML page using AJAX (really just JavaScript in this case).

Line by Line

Let's first dive right into and view the code of test.html. I'll put comments below to explain as we go along.

Ok this part is easy enough just some standard HTML code to get the page going, so far so good.

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<title>CCE's AJAX Simple Tutorial </title>

Ok so here we have our JavaScript code. This starts creates a function called createRequestObject. This will be the object that will go get our data for us, very simple. There is some quick version detection to satisfy both Internet Explorer and other web browsers.

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

function createRequestObject() {

var ro;
var browser = navigator.appName;

if(browser == "Microsoft Internet Explorer"){

ro = new ActiveXObject("Microsoft.XMLHTTP");

}else{

ro = new XMLHttpRequest();
}

return ro;
}

var http = createRequestObject();

Ok so now we have the object http with our request function built in. Now we have to tell it to do something, this happens next.

function sendRequest() {

http.open('get', 'tom.txt');
http.onreadystatechange = handleResponse;
http.send(null);

}

We made a new function called sendRequest. You can see it uses our previous object http. The first line in the function uses the get command to get a file, in this case it is statically assigned the text file tom.txt.

NOTE: Dynamic data can be used as well very easily, see our other tutorials for both PHP and Coldfusion on this subject.

Ok so now the object is told to watch for the response ( to find out the status ) and then told to actually get the file.

function handleResponse() {

if(http.readyState == 4){

var response = http.responseText;
var update = new Array();

Ok now this function handles the response of our last function. So let's see; it checks our http object for the readyState variable (the status) and checks to see if it is a 4 ( 4 means it worked). If it is a 4 then we assume the variable http.responseText holds the contents of the file, storing it to our new variable response.

Putting it all together - AJAX text into specfic tags

So now we have the contents of the file. We could stop here but I wanted just a little more than reading one file and then outputting it to the screen. I wanted this tutorial to grow with you. So what I did is made it so the text file can contain multiple lines of text and we access a specific line easily to put our site where we want it. To explain further let's look at the text file itself.

title|hi this is a message from tom

You will notice I have the word title followed by a | (shift + \ ) then the text I want to display. Title refers to the <div> where I want the text. I could have several of these if I chose, for example I could have.

header|this text goes into a div named header
footer|this text goes into a div named footer

So I can define several different places using <div> and access them. Now let's explain that a little bit more by looking at the next few lines of code. First I check to make sure the | symbol is there so I can tell what <div> I want it in and what is the text I want to display.

I then use the split function to split the variable at the | symbol, then storing it into a variable. I know have the div name in update[0] and the text itself in update[1].

if(response.indexOf('|' != -1)) {

update = response.split('|');
document.getElementById(update[0]).innerHTML = update[1];
}
}
}

</script>

Ok now this should all come together. I have a <div id="title"></div> which is empty. You'll remember the title from above in our text file. Now look at the function called in our JavaScript link, sendRequest(title). That means to put the data from the text file we defined but ONLY the line that starts with title| and then put it between the <DIV> tags labeled title. See how cool that is? Now we can use that text file to put as much text as we want. And then call that text and put it exactly where we want it.

<a href="javascript:sendRequest(title)" mce_href="javascript:sendRequest(title)">Load data into Title DIV below </a>

<div id="title">
</div>

</body>
</html>

Best uses for AJAX

Some cool things you can do with AJAX include, perhaps pulling a Coldfusion Blog Feed from a HTML page? That's something I'll work on in an upcoming tutorial.

See this in action

Download the source code

PHP Basic Questions

| No Comments

One great thing about PHP is it is great for people that are new to web programming, it's very easy to start with and also can get really technical for the veterans. PHP started as Personal Home Page tools, it was started to assist new users with programming. The syntax is very easy to use and is very inituitive. PHP is a good language to start on and learn the basics of programming. With the tutorials on this site you should be able to get started using PHP to create dynamic web sites.

How does PHP work?

PHP is a server side scripting language. So PHP does the work on the 'back-end', preprocessing web sites and inserting dynamic data before they are displayed. Unlike JavaScript which is a programming language that works while the page is being viewed by the browser on the users computer. PHP is very similar to Macromedia's Coldfusion and Microsoft's ASP.NET.

All you do is just embed the code into an HTML page and give it a .php file name extension and you are good to go.

What do I need to get started?

Two things; a web server running PHP on it and a HTML editor. Most web hosting companies (including ours 'shamless self advertisement') offer PHP for no additional cost. This is a major advantage over Macromedia's Coldfusion which is an extra charge for most hosting companies (except ours, we offer free Coldfusion hosting - 'sorry I couldn't resisit).

What are some uses for PHP?

PHP can handle the output from HTML forms, collect the data, then email it to someone or enter it into a database. You can even write your own online store, message forums, pretty much anything you can think of that uses data and writes to a database. In short to give the basics you can :

  • Access databases
  • Access files on your server
  • Access system commands
    • This is especially interesting - many system administrators could use this to run common applications on their server. For example I had an old Perl script that ran and cleaned up a lot of un-needed files on our server. That Perl script can still be used and call upon from PHP, very powerful stuff.

How much does PHP cost?

As state above PHP is free. How is that? Three words; open source software. Open source software is very different from non-open source software companies. The term means that the source code is available for all to see, anyone has the ability to view the code to see how PHP operates, the same can not be said about Microsoft's Windows code which is guarded heavily away. PHP and open source software as whole operates on a very large (and very wonderful) community, there is no giant corporate office that runs it. There are many resources out there to learn this stuff as you can see by reading this site :)

PHP Variables

| No Comments

Taking our first lesson; Hello World Example, we are going to spice it up a bit and use variables with our PHP file. Let's start right away by looking at an example then explaining what we did.

<html>
<head>
<title>CCE's PHP Tutorial</title>
</head>
<body>

<?php

$var = "PHP is cool";
echo "<p>$var</p>";

?>

</body>
</html>

As you can see the line we really care about is

$var = "PHP is cool";
echo "<p>$var</p>";

This says define a variable called $var and give it the data of "PHP is cool"; , then we simply display the data using the echo command.

Using Constants

You saw above how to create variables and display the data, now we are going to take a look at creating 'constant ' variables. Constant variables typically do not change. They work well at the top of document if you know that you need to define something that will not change, let's take a look at a sample:

define("SALES_TAX",.05);

This creates a constant with the name name and the value is Tom Fitzgerald. You'll notice that constants do not require the $ before the variable name, and variables are traditionally defined in all upper case. This is not required but it can be easier when reading your code so you know what is a constant and what is not easily. You can now view the value by doing...

echo SALES_TAX

Simple Calculations

Now let's do some simple calculations using our variables and constant.

define("SALES_TAX",.05);

$Amount_Purchased = 5.45;
$Tax_Amount = $Amount_Purchased * SALES_TAX;

This takes our constant SALES_TAX and our variable Amount_Purchased and multiplies the two to get the tax amount.

Note: Make sure if you are doing a calculation you are defining the variable correctly, for example:

This is the correct way $Amount = 3
This is incorrect $Amount = "3" ;
Quotes are used only when defining a text variable or something you don't want to ever run a calculation on.

This is pretty simple so far so lets just view some more simple calculations:

$var1 = 3;
$var2 = 5;

$total = $var1 + $var2;
$total = $var1 * $var2;
$total = $var1 / $var2

This shows how we can do easy addition, multiplication and division using our new variables, good job.

Format data with PHP

| No Comments

Now we can learn how to change the output of certain variables. For example if you have variable containing the number 3, what if you want to output it as $3.00, or $0.03 ? How can we do that easily? There are some other cool things we can do but as usual; lets actually view the code and then explain how to do it. There are two commands we start to use here, printf() and sprintf().

printf("format",$firstvariable, $secondvariable);
$variable = sprintf("format", $variable1, variable2);

printf() outputs formatted strings and the sprintf() does the same thing but instead outputs into a variable to be stored and used for later.

$variable1 = 'Tom';
printf("% says hello",$variable1);

Here we have the printf() function you will notice the % tells PHP to output the variable supplied as the second argument to the function. We could stop there but printf() has so many more neat functions, let see. What other things we can add to that lonely %. The syntax is as follows:

%padding-width.decimaltype

  • The padding is a padding character that we can use to fill in the blanks so to speak with the value we use is smaller than the formatting width specified. (We haven't done that yet). If you don't specify a padding character, no big deal; a space is used.
  • The - symbol makes the text left justified, if this is not present it will be right justified.
  • The width is the number of characters to pad using the padding character.
  • The decimal is the decimal places to use.
  • The type is the type of value, the command values are s for string or f for float (or numbers with decimal places)

For example if the padding character is 0 and the with is 3 and the value is 5 then output would be.

001

Ok enough of all that, let's see it in action!

$paycheck = 250;
$newvariable = sprintf("My paycheck is $%03.2f");
printf($newvariable);

The output would be :

$250.00

The $%03.2f is interpreted as follows; the % says to start outputting the variable. The 0 says to pad using variables. The 3 says to put 3 places to the left of the decimal point and the 2 says to go 2 places to the right of the decimal point.

Other Output Functions

Let's take a look at some other output functions, these are really quick simple examples, starting with Strtoupper().

strtoupper() - Converting to upper case

$newvariable = strtoupper($variable);
printf($newvariable);

Takes the $variable and outputs in all uppercase. You can use unfirst() to capitalize only the first letter in the string to uppercase, likewise ucwords() will upper case each word in the string to uppercase.

strtr() - Replacing values

$variable1 = "1 6 3";
$newvariable = strtr($variable1, "6","2");
printf($newvariable);

This takes $variable1 and reads the string, replacing 6 with 2, then outputs 1 2 3

substr() - Returns value inside of string at a specific point

$newvariable = substr("tommy", 2,4);

Reads "hello" and returns everything from the 2nd character to the 4th character. Outputting:

mmy

substr_count() - Counts number of times a given item is in a variable

$variable1 = "tom 123 tom 123 tom 123";
$find = "tom";
$numberoftimesfound = substr_count($variable1, $find);

In this case the variable $numberoftimesfound would have a value of 3 because it found tom 3 times in $variable1.

Using Date Format

Ok now we did some cool stuff, let's see how simple it is to use the date since that is used very heavily in most PHP applications. Like almost everything else in PHP, accessing the current date is very easy, let's take a look.

$today = date("d/m/y");

Would give the $today variable a value of 04/01/2006. Very easy! :)

PHP Hello World

| No Comments

This will be a really easy starter tutorial and will go over how to create a Hello World PHP application. I'll be doing a few of these easy starter tutorials then grow from there. We'll be doing PHP, Python & Ruby on Rails. So let's get started with PHP. I'm assuming you already have PHP installed.

Whatever text editor you use; type this data into the file.

<html>
<head>
<title> PHP Tutorial</title>
</head>
<body>
<p>This is only a test</p>
<?php
echo "<p>...from PHP</p>";
?>
</body>
</html>

Save it as test.php, then upload it to your web server.

Access the web site in your web browser and you should see the following output:

This is only a test

...from PHP

And there you have it! Easy wasn't it?

Line by Line Explanation

Basically the only line that has to do with PHP is the one that says :

<?php
echo "<p>...from PHP</p>";
?>

The <?php part means to start interpreting the following as PHP not HTML. The echo "<P>...from PHP</p>"; means to echo (display) the code <p>...from PHP</a> which of course is standard HTML. The quotes are necessary as the trailing ; to show the end of the line.

Flash backwards compatible

| No Comments

Writing Flash programs can be challenging because not all web browsers and computers are the same. Flash provides a quality presentation most of the time everything works fine on different platforms as long the Flash plug-in is installed. But what if you write an application for Version 8 and the viewer has Version 7? The short answer: it is a debacle. The Flash quality we have lauded here disappears in a flash (no pun intended).

Change DIV with JavaScript

| No Comments

This is a really basic example on how to change the contents of a <DIV> tag using JavaScript. I've used this in other examples but really wanted to spell it out here so everyone knows how easy it is. Let's begin with some simple code.

In this tutorial we'll go over how to install Python on your Windows PC and a quick 'Hello World' application.

  1. First download Python and run the setup - agree to all prompts. Easy.
  2. That's it! Python is now installed. Open up notepad and paste in the following code
print 'Hello world'

Save it as hello.py, and just open a command prompt and run the script like this

C:\> hello.py

Then you will see Hello World! It's great and simple. Next time we'll do some more advanced stuff, had to start somewhere.

Take a look at Marylandlawyersearch.net. It's a web site I created so I could help my law firm clients. The idea is simple, its a directory of all my clients. The site could be considered a mash-up. It takes my client data and uses Google's Map API to display them. I also use jQuery because its just so damn fast and helpful.

My first concern was how to get my data dynamically into the site. I didn't want to have to update it every time I added a new client. Well I'm kinda starting in the middle here. I've already created a program to hold all my clients. I did this extremely quick using Ruby on Rails. This tutorial assumes you already have your client data in a database and you can access it via XML. I'll come back later and show how I made my client data program. With Ruby on Rails it was extremely easy to put it all together.

Twitter Feed