Form Ajax : How to Create and Submit a Form Using Ajax

For the longest time, web developers were stuck submitting their forms in the normal way: Click a button, go to a processing page, redirect back.  However, now it is possible to submit a form without ever leaving the page with Ajax.  Ajax stands for Asynchronous JavaScript, which as stated before, basically means you can submit a form without ever leaving the page.

So how do you use form Ajax? First of all, we’re going use a JavaScript library called jQuery.  Don’t be scared of it though, jQuery makes JavaScript easy.  What jQuery allows us to do is use form Ajax without having to muck around with all the tedious JavaScript details (which trust me, is a GOOD thing).   Without further a due, here is how to submit a form with Ajax.

To download the full working code for this, click here.

Form Ajax Step 1:  The HTML Page.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
<html>
<head>
<title>Form Ajax Tutorial</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
//After the document has loaded, it adds the following handlers
//to the web page.
$(document).ready(function() {
//When the form with id="myform" is submitted...
$("#myform").submit(function() {
     //Send the serialized data to formProcessor.php.
     $.post("formProcessor.php", $("#myform").serialize(),
     //Take our repsonse, and replace whatever is in the "formResponse"
     //div with it.
    function(data) {
          $("#formResponse").html(data);
     }
);
return false;
});
});
</script>
<head>
<body>
<h2&gt;Form Ajax Tutorial</h2>
<p&gt; Fill out some information &lt;/p>
<form id="myform">
<input type="text" name="firstName" value="" /><br />
<input type="text" name="lastName" value="" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<div id="formResponse">
</div>
</body>
</html>

For anyone who is used to HTML programming, this should all look very familiar.  The only confusing part is the JavaScript, but I’ll explain that here.  The first bit just includes the jQuery library.  This is crucial for form ajax to work.  The rest of the function is explained below:

  • $(document).ready() – This will add handlers to your web page only after the entire page has loaded.
  • $().submit() – This will catch the click of the submit button so that it doesn’t submit the form the normal way, but the Ajax way instead.
  • $().post() – This is the part that sends out data to the processing file.  It also has a callback function that will modify our page to contain data that the processing file sent back.
  • $().serialize() – Takes our form data and puts it into an easy to parse format.

Form Ajax Step 2:  The Processing Page

1
2
3
4
5
6
7
8
9
10
11
<?php
//Get the information that was sent from the form.
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
 
//Get the unix time stamp.
$unixTimeStamp = time();
 
//Print output for out web page to catch.
echo "Hello $firstName $lastName.  The local unix time is <b>$unixTimeStamp</b>";
?>

The processing page is very important for making form ajax work correctly.  What this file does is catch the data sent by the form, and then prints out some information.  The form is waiting for this information, and then will add it to your page.  Note:  This file is a .PHP file.  You need to be running a web server (or have access to one) that can process php files.

Form Ajax Step 3:  You’re Done!

Form Ajax used to be pretty difficult, but now that their are JavaScript libraries like jQuery, MooTools, and Scriptaculous, it’s easier than ever.  To download the full working code for this example, click here.

Javascript Net PDF Viewer

When trying to view PDF files on the internet, you have a very limited number of choices.  The obvious one is to let the user handle viewing PDFs with something like Adobe Acrobat Reader.  However, some users don’t have Acrobat installed.  Or the file gets downloaded instead.  If you want an easy way to view PDF files online though, look no further than Google Docs.

The Google Docs Javascript PDF Viewer will embed the same javascript pdf viewer that Google Docs uses right in to your page via an IFrame.  It’s really that easy.  It even allows for searching of documents (which is quite handy!).  If this sounds like what you’re looking for, the link is below.

Javascript Net PDF Viewer [Google Docs]

iPhone and iPod Touch Development: Starting Out

Beginning iPhone 3 Development Book CoverLast Christmas I graduated from college.  One of my graduation gifts was a 2nd generation iPod Touch!  At the time, the iPod Touch was one of the coolest things I had ever got.  I immediately started to play with it, and was impressed with it’s ability to know the orientation of the device.  It’s multi-touch support was also impressive.  Probably the coolest part of owning an iPod Touch was that “there’s an app for that” attitude.  The sheer volume of available apps was mind blowing.

After graduation I started grad school, so I didn’t have much time to play on the technical side of iPod Touch and iPhone development.  However, I now have the time, and what follows is my journey on the road to iPod Touch and iPhone development enlightenment.

Getting Started

iPod Touch on top of "Beginning iPhone 3 Development"

The iPod Touch. A little banged up, but still amazing.

Before I even got started with iPhone development, I already ran into a problem:  I don’t own a Mac, nor do I want to own one.  It’s not that I don’t like them.  They’re beautiful machines with top of the line hardware and software, it’s just they’re a little outside my

price range.  So, how does one go about developing for the iPod Touch and iPhone on a Windows machine?  Well, there are a few different options.  Some revolve around Cygwin, while others around VMWare.  There is a good thread going on over at Stack Overflow (here) about it.  Depending on your situation, you may want to just pony up the cash for a Mac Mini, but to each their own.  In my case, I went with one of the methods listed above.

About the Book

The book I’ll be using for this adventure is “Beginning iPhone 3 Development:  Exploring the iPhone SDK” by Dave Mark and Jeff LaMarche.  It was reasonably priced, well reviewed, and had a grapefruit on the cover.  How could I possibly go wrong with this?  While I’ve only read the back cover at this point, the only problem I have with it is that it fails to mention the need for a Mac.  Some people might say “Duh!  Of course you need a Mac for iPhone and iPod Touch development!”, but it’s not always obvious to everyone.

Requirements

As with most development projects, there are a few things you need before you get started.  In the case of iPhone & iPod Touch development, you need the iPhone SDK (also, from this point forward I’m going to start referring to “iPhone & iPod Touch development” as “iPhone development”).  To get at the iPhone SDK, you need to visit http://developer.apple.com/iphone/ and sign up to be an iPhone developer.  It’s free (or has free options), so that’s a relief.

The sign up process seemed fairly painless.  While I’m not a huge fan of having to register and give out personal information, they control the SDK, so I suppose I must do as they say.  Nothing too suprising once you’re through the registration though, except the download is 2.5 GB!!! The worst part is that I have no idea why.  I always thought Netbeans with the JDK/JRE was huge, but this thing blows it out of the water.

Hello World

It’s a programming tradition to learn any new programming language with a simple “Hello World” program.  Even when not programming, some programmers still use “Hello World” to break the ice.  Hardly one to break with tradition, I’m going to be starting with a “Hello World” too, except this time for an entire platform, instead of just a programming language.

After much fumbling around, here are the steps to getting a “Hello World” program started.

  1. Open XCode and select New Project… from the File menu.
  2. Select View-based Application.
  3. Name your project Hello World.
  4. In the Groups and Files window, open the Resources group.
  5. Double Click the file Hello_WorldViewController.xib
  6. With the view now open, browse down the library until you find Label.
  7. Drag the label to the view.
  8. Double Click the label, and type “Hello world!”.
  9. Now go to File, then Save.
  10. Go back to Xcode and select Build, then Build and Run.

Honestly, I expected it to be a bit harder than this.  Next time I’m hoping to make it though chapter 3, where I get to learn how to handle basic user interaction!  As always, any feedback is welcome.

Using HTTPService to get XML results from a server

I’m not a Flex developer, but I’m quickly becoming one.  Recently I was tasked with creating a Flex form, sending it to the server, waiting for a response, and handling things accordingly.  My problem was that I couldn’t figure out how to use my result set that I received from the server.  Turns out, I needed to import a EventResult library, which was the turning point.

The Actionscript

import mx.rpc.events.ResultEvent;

private function thanks(evt:ResultEvent):void{
var dataFromServer:XML = XML(evt.result);
mx.controls.Alert.show(dataFromServer.toXMLString());
}

The Flex

<mx:HTTPService
id=”srv” useProxy=”false”
url=”http://localhost/form.php” method=”POST”
contentType=”application/x-www-form-urlencoded”
resultFormat=”xml” result=”thanks(event); “>
<mx:request>
<name>
{ bname.text }
</name>
<address>
{ baddress.text }

</address>
</mx:request>
</mx:HTTPService>

What happens here is that the HTTPService sends my data to the server, then some new data is returned in XML format.  Important things to remember are the ResultEvent that is passed to the event handler.  Just passing a normal event didn’t do much for me.

Still waiting…. but this time with a measure of patience!

I’ve been waiting for over 3 weeks to hear back from IBM.  I eventually heard from them, when they apologized for taking so long.  All this is understandable as they interviewed a TON of people.  The good news is that they want to offer me a job!  They bad news, is that they can’t give me my offer yet because of corporate red-tape.  It has to finalized, stamped, copied in triplicate, etc, etc.  Either way, I’m very excited to see what they have to offer.

I also got an interesting call today from MSU.  I applied for a position as a web developer there almost a month ago, and got a call to interview today.  I was caught off guard, so I hope I didn’t sound not-interested.  I have an interview with them on 12/15.  I look forward to hearing about the position, hopefully answering some interesting questions, and seeing what they have to offer.  While I doubt they can match IBM’s pay scale, they have other incentives like tuition reimbursement and then like, which make a job there very enticing.

Also, along a different line, I created a URL shortener the other day.  It’s called fwds.me.  It works like any other URL shortener, except faster :) *

That’s all I have for now.  I’ll leave an update when I’ve made some job decisions.

*It’s probably not faster, but it’s at least as fast as most other shorteners.  I use Apache mod_rewrite to handle the url, and then a quick sql query to find out the original URL.

Playing with Go: Channels and Go-Routines

Edit:  I’m implementing a new version of this that isn’t limited by overflow.  I’m doing this by adding the numbers on a per digit basis, carefully managing the overflow, and storing the numbers as strings.  Theoretically, we should be able to calculate LARGE Fibonacci numbers like this.

When I heard about Google’s new programming language Go last week, I immediately jumped on it.  I had used Limbo before for a distributed programming course, so I thought that I might write some code to help other people get their feet wet.

My example is a simple Fibonacci number calculator.  It works by creating a new Go-routine every time it needs to calculate the next number.  There are a couple different approaches to doing this:  Create the entire pipeline first (faster calculation, slower set up), Create the pipeline as we go (not a bad way to go, smaller overhead), or create a ring and have the calculation take place within the ring.  Communication between the Go-routines and the main thread are handled via channels.

I heavily documented the code so that beginners might be able to make sense of what’s going on.  If you have any questions, please leave a comment!

Download the code here.

/*
* Name:   fibonacci.go
* Date:   November 16, 2009
* Author: Jack Slingerland (jack.slingerland@gmail.com)
*
* Description:  This program is a Fibonacci number calculator.
*   It may be invoked as follows:  “./8.out [goal]“, where [goal]
*   is the Fibonacci number that you want to computer.  Currently
*   the program is limited to the 46th Fibonacci number due to
*   overflow, however a new implementation is in the works that
*   won’t have that limitation.  The real purpose of this program
*   is to show how Go-routines work, and how communication and
*   sychronization between them is handled using channels.
*/

package main

import (
“os”;
“fmt”;
“strconv”;
)

/*
*  This ADT holds all the information needed to calculate the next
*  Fibonacci number in the sequence.  Current is the current index
*  in the series (ex, 5 = We’re on the 5th number in the sequence).
*  Goal is of course, the number in the sequence that we’d like to
*  achieve.
*/
type fibonacci struct {
a int;
b int;
current int;
goal int;
}

func main() {
//Check the command line arguments for sanity.
goal, err := checkArgs();
if(err != “”) {
fmt.Fprintf(os.Stdout, “Error: %s”, err);
os.Exit(1);
}

//Special case:  If the goal is 2 or less, the Fibonacci number is always
//1.  This isn’t really worth creating channels + go routines for.
if(goal <= 2) {
fmt.Fprintf(os.Stdout, “Fibnonacci Value %d is: %d\n”, goal, 1);
} else {
//Construct two channels, the input channel acts as our communication
//between the Go routines.  As you can see, it can be typed as an
//ADT(struct), which makes passing data REALLY easy between go routines.
//The final channel is for passing back the goal Fibonacci number to
//the main thread.
input := make(chan fibonacci);
final := make(chan int);

//Create a new fibonacci object and set it’s values.
var x fibonacci;
x.a = 1;
x.b = 1;
x.current = 2;
x.goal = goal;

//Create a new Go routine with the addNumber function.  We pass it the
//two channels that were declared earlier.  This is similiar to “spawn”
//in Limbo.
go addNumber(input, final);

//The first addNumber() Go routine will block until it gets input from
//the input channel.  So, we pass it our fibonacci object.
input <- x;

//Now, we block and wait for the Go routines (addNumber()) to finish up
//and send us back the final value.
number := <- final;

//Print the value out and we’re done!
fmt.Fprintf(os.Stdout, “Fibnonacci Value %d is: %d\n”, x.goal, number);
}
}

/*
* The addNumber() function takes two channels as parameters.  One is a
* channel of fibonacci, which holds information about which number to
* calculate and when to stop, and then a channel of type int, which will
* be used to send the final goal number back to the main thread.
*/
func addNumber(input chan fibonacci, final chan int) () {
//Block here and wait for input from the previous thread
//or the main thread, depending on the situation.
x := <- input;

//Here we check to see if we have met our goal, if we
//have, we return the goal value back to the main thread
//via the final channel.  Otherwise, we calculate the
//next number in the sequence.
if(x.current < x.goal) {
fib := x.a + x.b;

//This is fun because you can assign multiple values at once.
//x.a <- x.b and x.b <- fib.  :)
x.a, x.b  = x.b, fib;
x.current = x.current + 1;

//Make a new channel of type fibonacci so that we can communicate
//with the new Go routine that we are about to create.
output := make(chan fibonacci);

//Pass the new Go routine the newly created channel, as well as the
//final channel that was passed in from the caller.
go addNumber(output, final);

//Send the fibonacci object out on the channel.
output <- x;
} else {
//Send the goal value out on the channel back to main.
final <- x.b;
}
//Go routine dies now.
}

/*
* The checkArgs() function is a great example of returning multiple
* values.  We return an integer and a string to the caller, so handling
* errors is fairly straight forward.
*/
func checkArgs() (int, string) {
//Fetch the command line arguments.
args := os.Args;

//Check the length of the arugments, return failure if that are too
//long or too short.
if((len(args) < 2) || (len(args) >= 3)) {
return -1, “Invalid number of arguments.\n”;
}

//Convert the goal argument to an integer.
goal, err := strconv.Atoi(args[1]);

//Make sure the conversion went correctly, otherwise return failure.
if(err != nil) {
return -1, “Invalid argument.  Argument must be an integer.\n”;
}

//Since this implementation is limited, make sure the user can’t go
//beyond the program’s limits.
if(goal > 46) {
return -1, “This program only calculates up to the 46th Fibonacci number.\n”;
}

//Check the lower bound as well.
if(goal < 1) {
return -1, “Invalid range.  Number must be >= 1.\n”;
}

//On success, return the goal value and an empty string indicating
//that everything is good.
return goal, “”;
}

Geocities : Salvaged

As much as it pains me to look at, I decided to salvage one of the earlier web pages that I ever made.  I have long since forgot earlier web pages, but “The NannyMUD Guide” really stood out to me because it was my first serious effort at web development.

It’s nasty sure (big crappy flash animations, talking to myself, awful menu design, crap color scheme,…), but it was an important to me then.  Click the link below to check it out.

The NannyMUD Guide

Edit:  I’ve been asked for a quest walk-through for NannyMUD.  Click here to download it.

Functional Programming with Erlang

For the past 8 weeks in my graduate operating systems course, we’ve been dealing with the issues of inter-process communication in massively parallel situations.  For development of such applications, we’ve been using an operating system called Inferno (of Plan 9 origins) which has a built in language called Limbo.  Limbo is a great language for learning network programming and multi-threaded programming.  It has communication channels which are typed, so you can pass whatever you want along them without pre-processing the data.  However, you still have to manage all of those channels.  It also has a nice C + Pascal style syntax:

message := “Hello World!”;
sys->print(“%s\n”, message);

While discussing languages that support massive concurrency with my professor, the subject of functional programming came up.  I mentioned to him that I wanted to learn a functional language, but wasn’t sure where to start.  He suggested Erlang due to it’s easy support for massive concurrency.  My question to my readers (if I have any left), is do you have any experience with programming multi-threaded and/or distributed programs with Erlang?  Is it worth the time to learn, or would my efforts be better off elsewhere?