Archive for the 'HTML_AJAX' Category

What i’ve been up to

Monday, March 12th, 2007

I haven’t blogged lately but I’m going to try to get with it again. Last month I finished up a big project built on top of Wordpress, and then started a new job. I’m doing less PHP coding in my day job for the time being which has been a nice change.

I’ve also been doing a lot more work on phpDocumentor lately, I’ve been mainly been focused on code review since Chuck Burgess has been getting tons of patches ready. We’ve also started planing for 2.0 release, so hopefully will get the large project performance problems fixed in the next 6 months. In the shorter term was almost ready to do a bug fix release, thanks to Chuck’s work a the majority of the outstanding bug have been fixed.

On the HTML_AJAX front there is a 0.5.1 release that is almost ready to go (I fixed a bunch of bugs last week) but it still needs more testing. Because of the testing problems I’ve finally started writing some unit tests for it. I’ve been focusing on the JavaScript side, using jsunit. Hopefully i’ll have enough tests done by the end of the week to feel comfortable about releasing. The code is pretty close to 1.0 at this point, its just a matter of writing tests, finishing the manual and adding a bit of polish. Let me know if your interested in helping out. Polish and documentation aren’t the most interesting parts of Open Source development but its one of the most important parts.

I haven’t got any new AJAX work to a state where I could do a real article but I have been playing around with some new stuff. Last week I started experimenting with Dojo, I wasn’t really happy with the state of its documentation, which is really problematic because of the enormous size of its API but it does have a lot of neat features. What interested me most was its Cross Domain XMLHttpRequest support, Its based on running the XMLHttpRequest requests in a separate IFrame and then loading the results back by modifying the Fragment identifier on the parent document.

I’d also like to point out that there has been that JQuery 1.1 has been released (and a couple bug fixes releases since then). It cleans up the API bit and has some nice performance enhancements. If your using JQuery its an upgrade well worth doing.

I’ve also been working on WebThumb a bit. No big changes but I have worked out all the PayPal integration bugs. I’ve also got enough paying customers to pay for some server upgrades should be done by the end of the month. I was hoping to have a new server running month but I’ve ran into some snags. I have the new server ready to ship to the Co-lo but it seems its all maxed out on power so we can’t use the rest of the space in the rack. Hopefully things will be figured out soon. I’ll be adding at least one new feature to WebThumb this month so if you have some feature you’ve been waiting for let me know, maybe your request will be the next addition.

Deciding What AJAX Programming Style to Use

Thursday, January 4th, 2007

In my AJAX book, Understanding AJAX, I spend a lot of time talking about the various programming styles you can use with AJAX. Looking back at the chapter it seems to me there are 2 major styles of programming and large number of varitions depending on what data encodings were using, and where the bulk of our programming actually happens.

Looking at my own day to day development I tend to fall into a couple main approaches.

  • AJAX page chunks (sending standard GET/POST requests, and updating part of the page by innerHTMLing in the respose)
  • RPC using generated proxies
  • Widgeted AJAX using RPC in the background

Now each of these approaches has its advantages and disadvantages. AJAX page chunks are easy to understand, on the PHP side im generating HTML using a standard MVC framework, and I can just turn off my outer wrapper for the chunks. The disadvantage is that my JavaScript code doesn’t have a lot of power in this approach. I’m skipping full page reloads but I still might be updating a large percentage of the page for a very small change. Its also hard to update disperate parts of a page. To solve this I sometimes find myself returning an array of HTML chunks but this quickly leads to both the PHP and JavaScript sides of the equation getting overly complicated and brittle.

AJAX Page chunks are especially nice when dealing with forms, you just serialize the form to a query string, POST it to the PHP side and return the updated form, replacing the innerHTML of the forms parent with an updated form. I consider page chunks to be my first option, they make it easy to use a single code base to support AJAX and non-AJAX operation, and most importantly are an easy concept for new developers to pick up. It also leverages current skills and keeps the amount of JavaScript down since devlopers are more likely to look towards PHP (or whatever backend lanuage you use) to solve there problems.

RPC style AJAX using generated proxies is very powerful while still being pretty simple. HTML_AJAX makes programming in this style extremly easy to implement. On the PHP side I write a class that becomes the external API to my application. HTML_AJAX covers exporting the API and encoding the data, and on the JavaScript I get a generate proxy that makes that API easy to work with.

Then its time to write a lot of JavaScript code. The biggest benefit of any RPC approach is you have data in your JavaScript not just some HTML. I tend to use an approach like this when i’m building a JavaScript application. It tends towards a more client server model and moves things away from a standard MVC approach. The biggest disadvantage to this approach is the complexity. You end up with huge amounts of JavaScript code, and much smaller amounts of PHP. This wouldn’t be horrible if JavaScript was mature and consistent on all browsers but its not. Plus you can’t trust the client so the PHP code still ends up being larger then you’d like since it has too enforce all the security and integrity rules of the application. But at the end of the day sometimes you need the power.

The last style I use is related to the more standard RPC approaches but I’ll often use it along with AJAX page chunks. With widgeted AJAX I develop a self contained set of HTML and JavaScript code that can be easily integrated into any page. This might be a autocomplete/suggest style dropdown or a live grid. I normally use RPC on the backend inside these widgets since they need actual data but what there using doesn’t really matter. The point of the widget is too make things self contained enough that they can be easily integrated with anything.

Looking at these styles I think each can have it place, but I think my decisions on what to use are more and more driven by simplicity. When looking at a problem whats the simplest solution. The more I use AJAX the more I see that its added complexity is its biggest problem. Like any other programming the simplest solution is usually the best one.

I’d like to hear your thoughts on the matter, what AJAX programming styles do you use and why?

New tutorial using HTML_AJAX and PEAR::Pager

Wednesday, October 4th, 2006

Lorenzo Alberton wrote a nice tutorial combining PEAR::Pager and HTML_AJAX. Its amazing how easy things get when you have some good libraries to rely on.

HTML_AJAX reaches beta

Wednesday, August 30th, 2006

Yesterday we released HTML_AJAX 0.5.0

It contains lots of bug fixes and a couple new features, but the biggest change is this means were commiting to a stable API. Between this release and 1.0 will be in a feature freeze, focusing on improving documentation and fixing any problems.

You can upgrade by running pear upgrade HTML_AJAX-beta

AJAX Answers

Thursday, August 17th, 2006

The last couple days have been a lot of fun. I was at LinuxWorld and did a book signing yesterday, my publisher had the first copies of Understanding AJAX at their booth. They should be showing up at bookstores and Amazon in the next couple weeks.

Your AJAX answers from my AJAX questions post are below, I hope everyone finds them helpful.

Dealing with broken connections

Question:

How can I find out whether a connection is broken? Should I just set a unique timeout per request after which an error message can be displayed? The timeout would be deactivated if the AJAX call succeeds. Is this a smart idea and does it work?

Answer:

Using a timeout per request does work though its not a perfect solution. HTML_AJAX uses this approach, and a default timeout of 20 seconds. The issue is that 20 seconds is a long time to wait to provide an error, but there are still cases that hit this value. Its also hard to know what to do if you’ve hit an error, is this a transient failure and you should resend your request, or can you know longer talk to the server and you’re app needs to provide and error.

HTML_AJAX vs Prototype

Question:

Why would you want to use HTML_AJAX when there are far better tools for the job, pure javascript solutions such as prototype or jquery? I don’t think you need something special on the serverside to return some data as a response to an AJAX call.

Answer:

I guess you don’t like HTML_AJAX, which is ok, but there are lots of reasons why developers want AJAX libraries that are closely tied to there server side language. Libraries like HTML_AJAX make it easy to perform RPC style AJAX, and they usually make it possible to write less JavaScript on just focus on your primary server side language. Though these libraries do this to varying degrees of success. Something like SAJAX just handles the RPC, while HTML_AJAX can be used with very limited JavaScript writing (HTML_AJAX_Action stuff), and most of the .NET AJAX libraries allow you to add AJAX with no JavaScript at all, since the .NET code behind concept make its really easy to automatically chunk up your code.
Even if there is a JavaScript library you think its great, that doesn’t mean it offers the tools that everyone wants.

Degradable AJAX sites and JavaScript behaviors

Question:

What is the best way to ‘degrade’ a website when Javascript/XMLHttpRequest support is disabled? Take f.e. yahoo.com. It’s a great website enriched with AJAX, but when JS is disabled it’s still looks the same but the rich features are not there. Would you consider CSS-style selectors as the solution? I do not want to create two different websites, one JS enabled and the other JS disabled. Thank you in advance.

Answer:

CSS-style selectors, like those you use with the Behavior library gives you a good tool to write a degradable AJAX site, but the actual implementation can be pretty hard.

In general it means fully implementing a site without AJAX, then picking forms, links, etc that you want to make AJAX and tieing the AJAX too them at runtime. This works really well if your just doing something like type-ahead search since your not changing work flows, but it doesn’t always work that great for form submissions, since they often update different parts of the page, and the code that processes them is generally designed to build the whole page.

If your using AJAX for enhancements that don’t change the actual work flow then making your site degrable is easy. If your site relies on AJAX for its basic workflow you’ll have a much harder time making a site degrade.

Attaching JavaScript using css selectors is a great approach since it keeps your HTML completly seperate

Adding JavaScript on using AJAX

Question:

When utilizing an AJAX API such as Google Maps, how do you execute embedded Javascript commands in a page generated on-the-fly? For example, you have a website which contains several ’s, one of which is an implementation of the API (i.e. a Google map). That loads when the page loads. Now, based on user interaction (clicking on links), you pull an SQL result from a database and display 10 at a time in a separate . Each time the loads, you want to execute some commands through the AJAX API. In my understanding, JS only executes at the browser page load, but I’m sure I’ve seen sites that get around this.

Answer:

While its true that you can’t directly add JavaScript too a page using script tags and innerHTML, that doesn’t mean you can’t add JavaScript to your page at any time. The simplest way is too just send your new JavaScript as text and run it through eval too add it too the page. You can also parse your strings before adding them with innerHTML and run eval as nesseccary. HTML_AJAX provides a method for doing this parsing for HTML_AJAX_Util.setInnerHTML. If you use it JavaScript in any script tags will be run. Other libraries like prototype also offer similar features.

AJAX File Upload

Question:

how can i make a file upload via ajax?

Answer:

If you think of AJAX as involving using XMLHttpRequest then you can’t (at least not without disabling the browsers security model, which i don’t even recommend for intranet apps). But you can still upload files asyncronously, its just a matter of targeting a form at a hidden iframe. You will also want to look at generating your IFrame in JS since i believe it gives you less problems with browser history.


<iframe name="upload" id="upload"></iframe>
<form target="upload">
<input type="file"/>
</form>

AJAX Form Submission

Question:

I’ve been studying AJAX for a bout a month now but I have not yet grasped the tecnique to submit a form with POST method. I’ve been trying to find an article that covered that but all I could find was the ones that included somekind of already made framework.

I want to know how to submit data to server (like form or email sending) with POST method.

Answer:

Submit a POST request using AJAX you first have to understand what a normal form POST is.
When you submit a form in your browser it makes a http request with the following options:
HTTP Verb: POST
Content-Type: application/x-www-form-urlencoded
And a body of something like:
fielda=valuea&fieldb=valueb

So to replicate a form POST in AJAX you need to run xmlhttp.open with POST set a header, xmlhttp.setRequestHeader(’Content-type’,'application/x-www-form-urlencoded’);

Then encode your content and send it.
xmlhttp.send(’fielda=valuea&fieldb=valueb’);

If you use a library most have code for handling this for you, HTML_AJAX has HTML_AJAX.formSubmit for taking a form and submitting it using AJAX and HTML_AJAX.post for doing custom POSTs.

You got AJAX questions I got Answers

Friday, August 11th, 2006

Have you wondered whats the easiest way to submit a form using AJAX, what the status of HTML_AJAX development is, or what is covered in Understanding AJAX?

Well nows your chance.

Submit your questions general AJAX questions, questions about my soon to be released book Understanding AJAX, questions on HTML_AJAX, or anything else I might know the answer of, and I’ll answer them in another post a couple days from now.

Adding AJAX to a Website step by step, Part II

Thursday, August 10th, 2006
I have a lot more change's i'd like to make to webthumb so the last article (Adding AJAX to a website step by step) is now the start of the series. In this article will be taking front page of webthumb and making it live. The the stats and recent thumbnails will update in real time, making for a nice slick presentation. Webthumb Frontpage

I hope to release and article for each improvement I make to webthumb, giving everyone idea of whats involved in AJAXing a real website. But a series of articles won't cover everything you want to know about AJAX. If your interested in learning more you should take a look at my book, Understanding AJAX (should be shipping september 1st), it covers everything from basic AJAX implementations to usability and debugging.

Getting realtime data with AJAX

The frontpage of webthumb could be updated with each new thumbnail that is created. In straight HTML you might handle updating things by using a meta refresh. The problem with this, is your loading a lot of repetitive content, and the full page refresh makes for a clunkly look.

With AJAX you can poll the server on a regular interval and just update things when data has changed. Polling approaches can cause scalability problems since they can create a large number of requests to your server. Hopefully this won't be a problem in this case since i'll be making small requests and returning a large amount of data, and I don't need to make them that often. There is also an alternate approach that you can use called comet, that works by each client keeping a connection open to your server and pushing data to them. But a push approach brings about a whole new set of scaling problems, so will stick with tried and true polling, and i'll cover comet some time in the future.

Exporting the PHP Class

Like the last upgrade will be using HTML_AJAX for our AJAX communications. On the server side I created a new class called WebthumbStats, it has a single method named "updatesSince", that takes a timestamp as its parameter. If you were using it in php you'd get something that looks like:

<?php

$stats = new WebthumbStats();
$update = $stats->updatesSince($lastPoll);

?>

If nothing had changed since my last poll i'll get a timestamp back. If something has changed I'll get an array of data back containing the basics stats, a timestamp, and the new image ids. Will use the timestamps from the server when making the next poll request that way we don't have to worry about problems with the client's time settings messing things up. A result might look something like:

<?php

array(
  'queue' => 1,
  'lifetime' => 1324,
  'today' => 329,
  'time' => '2006-08-07 16:45:01',
  thumbs => array(
    array (
      'img' => '/webthumb/data/ba86/wt44dac13bcba86-thumb_medium.jpg',
      'url' => 'http://bluga.net',
    ),
    array (
      'img' => '/webthumb/data/46d6/wt44dac3c4546d6-thumb_medium.jpg',
      'url' => 'http://blog.joshuaeichorn.com',
    )
  )
);

?>

After writing the PHP class I wrote a small test script in PHP and made sure it was working right, then I registered it in ajax.php.

<?php

require_once 'HTML/AJAX/Server.php';

class WebthumbServer extends HTML_AJAX_Server {
        var $initMethods = true;

        function initRequestStatus() {
                require_once 'lib/RequestStatus.class.php';
                $this->ajax->registerClass(new RequestStatus(),'RequestStatus',array('getStatus'));
        }

        function initWebthumbStats() {
                require_once 'lib/WebthumbStats.class.php';
                $this->ajax->registerClass(new WebthumbStats(),'WebthumbStats',array('updatesSince'));
        }
}

$server = new WebthumbServer();

$server->handleRequest();

?>

You'll notice the basic registration is the same style as we used for RequestStatus but now its enclosed in a class. The init method functionality in HTML_AJAX_Server gives you a way to organize how the PHP class are setup for AJAX access. It also means that when a request is made to RequestStatus WebthumbStats code won't be loaded. With just two classes this doesn't save a ton of overhead, but every lit bit helps, and when you get too 20 or 30 AJAX classes it can make a huge difference.

Polling with HTML_AJAX

The JavaScript side is really simple. We poll on a set interval, with a check to make sure we aren't waiting on another poll to finish. Other then that its just a matter of getting a starting timestamp from the server when we generate the page. The polling code looks like:


HTML_AJAX.defaultServerUrl = 'ajax.php';
var inProgress = false;
var statsInterval;
var lastPoll = '< ?php echo $now; ?>';

function setupStats() {
        statusInterval = window.setInterval(statsUpdate,8000);
}
function statsUpdate() {
        if (inProgress) {
                return;
        }

        inProgress = true;

        HTML_AJAX.call('WebthumbStats','updatesSince',statsCallback,lastPoll);
}
function statsCallback(result) {
        inProgress = false;
        if (result.time) {
                // do something with updates here
                lastPoll = result.time;
        }
        else {
                lastPoll = result;
        }
}

Updating contents on new data

Lets start with updating the basic stats since thats the easy part. We just give the div containing each of the statistics an ID and then replace there innerHTML with the new content. This code looks looks like:


$('queue').innerHTML = result.queue;
$('lifetime').innerHTML = result.lifetime;
$('today').innerHTML = result.today;

Updating the thumbnails is a little harder since we want to add new thumbs on the left of the list and drop the old ones off the right. The thumbs array we have returned is shown oldest first, so we can just append to the begining of the list and delete from the end. Using a little getElementsByTagName, insertBefore and remove child lets us make the image updaes a reality.


                var images = $('recent').getElementsByTagName('div');

                for(var i = 0; i < result.thumbs.length; i++) {
                        var newImg = images[0].cloneNode(true);
                        newImg.getElementsByTagName('img')[0].src = result.thumbs[i].img;
                        newImg.getElementsByTagName('a')[0].href = 'pickup.php?id='+result.thumbs[i].id;
                        newImg.getElementsByTagName('a')[1].href = result.thumbs[i].url;
                        newImg.getElementsByTagName('a')[1].innerHTML = HTML_AJAX_Util.baseURL(result.thumbs[i].url.substring(7));

                        $('recent').insertBefore(newImg,images[0]);
                        $('recent').removeChild(images[4]);
                }

The line using HTML_AJAX_Util.baseURL is updating the domain below the image, were using baseURL just like you would use basename in PHP. This domain chopping keeps long urls from making the list look bad.

Using HTML_AJAX to manage JavaScript library delivery

HTML_AJAX delivers its JavaScript libraries through HTML_AJAX_Server. This code can also be used to deliver any other JavaScript library you want. Its main features are, setting headers for client side caching, and allowing you to easily combine multiple files together so clients don't have to open as many connections to your server.

To finish this update, I'm going to need moo.fx so my first task is too register it with my server.

<?php

$server->registerJsLibrary('moofx',array('prototype.lite.js','moo.fx.js'),'/home/htdocs/javascript/');

?>

This registration makes the keyword moofx delivery the prototype lite depenency and the moo.fx library. These files are grabbed from /home/htdocs/javascript on my server.

Then i just update my include to pull in moo.fx


<script type="text/javascript" src="ajax.php?client=html_ajax_lite,alias,moofx"></script>

Adding some Effects

The auto updating stats are neat, but the change is so subtle people might not notice its happening. To make it clear an AJAX update is happening I'll add a couple effects.

I'm going to animate the height down to zero on a thumbnail before I delete, and fade in the next text on my stats boxes.

To do a fade you create a new Opacity animation


var fadeIn = new fx.Opacity($('StatusBoxes'));

Then you call its custom method giving it the starting and ending opacity.


fadeIn.custom(.1,1);

The same approach is used to shrink the thumbnail out, only this time will set some options.


var shrink = new fx.Height(images[3],{duration:1000,onComplete:function()
                                {
                                        $('recent').removeChild(images[3]);
                                        $('recent').insertBefore(newImg,images[0]);
                                }
                        });
shrink.custom(160,0);

I use the onComplete event handler to remove the element when im done shrinking it and too add the new one.

Thats all for now

We covered a lot of ground in this article, some old some new. If you have any suggestions, or requests for further explanation please leave a comment.


Adding AJAX to a website step by step

Tuesday, August 8th, 2006

Update: The next article in this series is now complete.

Webthumb is a small project of mine that takes a snapshot of a website and gives you thumbnails in 4 different sizes. Currently the site is rather boring and has a couple of usability problems especially on the pickup page. Over the next couple of days I'll be using various AJAX techniques to upgrade Webthumb, writing about the process as things happen.

When looking at a adding AJAX you have a couple decisions you'll want to make up front. One is what tools your going to use. In the webthumb case thats pretty easy. Webthumb is a simple PHP app and doesn't use a framework, so I need a nice general PHP/AJAX framework that is easy to use, HTML_AJAX fits that need. I may also need so animations or other effects, since im not planning on doing anything really fancy i'll use the extremly small but powerful moo.fx. I'll also keep scriptaculous in mind if I end up needing something fancier, but I think its overkill for this project.

After picking my tools I need to decide what my goals are. My main focus will be to improve usability, but I also want to use AJAX to make the site seem a bit flashier, so its a bit of a technology demo too.

Updating Thumbnail Pickup

The first page im targeting is the thumbnail pickup page. Thumbnail generation is an asyncronous process, you make a request which is added to a queue and the thumbnail processor walks the queue generating thumbnails updating the status when its done. The current way this is handle is by letting the user reload the page a bunch of times, but the speed of thumbnail generation isn't consistent so if things run slow its easy to thing something is broken. I'll be fixing this by using AJAX to poll the server on a 1 or 2 second interval, and use that information to make some sort of a progress bar.

HTML_AJAX and PHP remoting

HTML_AJAX supports a number of different ways to add AJAX to your pages, in this case I've chosen to use its PHP remoting supporting. This works registering a PHP class to be used by JavaScript, and then using a proxy object from JavaScript to make calls or making calls with the classname and methodname specified. Since im only going to be making a few calls im not going to be using a proxy object, if you want some examples on how that works checkout my Hello World with HTML_AJAX post.

The RequestStatus PHP class

The class i'll be exporting too JavaScript is call RequestStatus it currently has a single method, getStatus. If you were using it in PHP a call would look something like:

<?php

$status = new RequestStatus();
$jobStatus = $status->getStatus($jobId);

// job is in queue
if ($jobStatus['status'] == 'queue') {
  echo 'Job is in Queue, there are '.$jobStatus['wait'].' jobs in front of it';
}
else if ($jobStatus['status'] == 'processing') {
  echo 'Job is being processed, it started at'.$jobStatus['start'];
}
else if ($jobStatus['status'] == 'complete') {
  echo 'Job is complete';
}

?>

Exporting a PHP Class

The easiest way to make a PHP class available to JavaScript is too use the HTML_AJAX_Server class. If your using a framework you can either integrate this class into your front controller to handle AJAX dispatch or you can use the HTML_AJAX class directly and write your own equivalent of HTML_AJAX_Server to handle call dispatch. I run HTML_AJAX_Server inside of a file called ajax.php, an example of which is shown below. The only item of note is that im specify the methods on that class to export, doing this is always a good idea, and its the only way to keep method case in php4.

<?php

require_once 'lib/RequestStatus.class.php';
require_once 'HTML/AJAX/Server.php';

$server = new HTML_AJAX_Server();

$server->registerClass(new RequestStatus(),'RequestStatus',array('getStatus'));

$server->handleRequest();

?>

At this point a good thing is test that the class has been registered correctly and isn't thowing any PHP errors. To do this load the generated JavaScript stub up in your browser, ajax.php?stub=RequestStatus. For any class the result should look something like below:


// Client stub for the RequestStatus PHP Class
function RequestStatus(callback) {
	mode = 'sync';
	if (callback) { mode = 'async'; }
	this.className = 'RequestStatus';
	this.dispatcher = new HTML_AJAX_Dispatcher(this.className,mode,callback,'/webthumb/ajax.php?','JSON');
}
RequestStatus.prototype  = {
	Sync: function() { this.dispatcher.Sync(); },
	Async: function(callback) { this.dispatcher.Async(callback); },
	getStatus: function() { return this.dispatcher.doCall('getStatus',arguments); }
}

Making AJAX calls to RequestStatus

Now that the backend is setup its just a matter of making some AJAX calls on the thumbnail pickup page.

To do this we'll create a new JavaScript function will be run by the pages onload handler. It will start a timer that makes a call to getStatus every 2 seconds, as long as another request isn't currently being waited on. Will be using HTML_AJAX.call to make the requests.

To get the needed JavaScript libraries I specify a client parameter too ajax.php. Im grabbing all the default libraries and the optional alias library. Alias lets me type $('id) instead of document.getElementById.


<script type="text/javascript" src="ajax.php?client=all,alias"></script>

My status code check code is pretty simple, if the status is complete is reload the page, and let the PHP code display the images. If not I display a new status message, either the items ahead of this thumbnail job in the queue, or the time that processing started on the thumbnail. I also added a simple animated loading gif. The status check JavaScript is below, followed by the HTML it updates.


HTML_AJAX.defaultServerUrl = 'ajax.php';
var inProgress = false;
var jobId = '< ?php echo $jobId; ?>';
var statusInterval;

function setupStatusCheck() {
        statusInterval = window.setInterval(statusCheck,2000);
}
function statusCheck() {
        if (inProgress) {
                return;
        }

        inProgress = true;

        HTML_AJAX.call('RequestStatus','getStatus',statusCheckCallback,jobId);
}
function statusCheckCallback(result) {
        inProgress = false;

        if (result.status == 'complete') {
                window.clearInterval(statusInterval);
                window.location = '< ?php echo $_SERVER['PHP_SELF']; ?>?id='+jobId+'&reload=true';
        }
        else if (result.status == 'processing') {
                $('statusMessage').innerHTML = 'Thumbnail generation started at '+result.start;
        }
        else if (result.status == 'queue') {
                $('statusMessage').innerHTML = 'Your thumbnail is in the processing queue, there are '+result.wait+' items ahead of it';
        }
}

               <div id="statusBlock">
                        <p id="statusMessage">Your thumbnail is in the processing queue, there are < ?php echo $waiting; ?> items ahead of it.

This page will automatically update when the thumbnail is complete.

<img src="loading.gif"/>
                </div>

There are a number of other enhancements we could make to this page. First it could use some CSS cleanups to look nicer. You could also skip the last reload by adding the images using JavaScript. And finally I could make a nicer way to show the 4 thumbnails. These enhancements and some some fun project on the front page will be covered in future articles.

Oh and these changes are live, so you can check them out by visting webthumb and putting in a url.


Understanding AJAX Digital Shortcut Available

Thursday, August 3rd, 2006

A chapter from my book, Understanding AJAX has been made available as a digital shortcut. This chapter covers the different ways you can use the data you transfer using XMLHttpRequest.

Document centric approaches based on HTML and XML are described as well as various RPC approaches are shown.

Personally i tend to use JSON based RPC approaches or HTML document based approaches. Document based HTML approaches let you add AJAX support without radically changing your development model, since its just a matter of breaking your pages into small chunks and generating HTML just like normal. RPC approaches allow you to develop JavaScript driven apps, which is great for quick prototyping and small apps, since you can write a backend in PHP and have it made immediatly accessible (at least if you use a library like HTML_AJAX to do the work for you) to your HTML and JavaScript frontend.

In Clearhealth we use both approaches. JavaScript widgets like our patient selector make RPC requests. While screens like the claim editor make standard HTTP POSTs treating each form section like it is its own page.

I don’t do much work with AJAX and XML, but client side XSLT can be a good solution if you need to move lots of data since it tends to scale better to extremly large datasets (especially in IE).

If your interested in the details of these various approaches grab the digital shortcut or pickup Understanding AJAX.

HTML_AJAX Wordpress Plugin Tutorial

Monday, June 26th, 2006

I found a handy tutorial of building a stock lookup plugin for Wordpress using HTML_AJAX. Shows how easy HTML_AJAX makes AJAX.

The only problem I see is the code won’t work in PHP5 since introspection will return the method name as GetQuote instead of getquote.

You can fix this by adding the following to the HTML_AJAX_Server instance.

// Create the HTML_AJAX Server
$objServer = new HTML_AJAX_Server();

// Set php4 case compatability so this code will work in 4 or 5
$objServer->ajax->php4CompatCase = true;

The other option too fix this is too set all the methods you want to register which is my prefered fix since it lets you have nice case in your JavaScript functions in php4

    // Create the HTML_AJAX Server
    $objServer = new HTML_AJAX_Server();

    // Create an instance of our stock quote class
    $objStockLookup = new StockQuote();

    // Register the stock quote object with the HTML_AJAX server
    $objServer->registerClass($objStockLookup,'StockQuote','GetQuote');

If you did this you’ll also have to update the JavaScript to use the cased version of the functions.

I’ve been away, but I’m back

Sunday, June 11th, 2006

As you may have noticed I haven’t been bloggiing much lately, but there are a couple good reasons why.

First I’m getting married, planning the wedding tends to take a bit of time.

Second i’ve been working really hard to get a book about AJAX done.

The book is finally into production and I’m just starting to get some chapters back from the copy editor.

I do have one thing to share with you today, the books cover.
The complete title is: Understanding AJAX: Using JavaScript to Create Rich Internet
Applications
The ISBN is 0132216353

Understanding AJAX book cover

Also im still finishing up the books appendices which list AJAX libraries, so if you know of AJAX libs for various languages please let me know, im especially interested in AJAX libs for C#, Java, Perl, and Python I already keep up pretty good with all the PHP ones, and most of the non backend language specific ones.

HTML_AJAX 0.4.0 is released

Friday, April 7th, 2006

HTML_AJAX 0.4.0 has been released. You can upgrade using the PEAR package manager in the normal ways.

The biggest new feature is the addition of a setInnerHTML method that runs any JavaScript in the string your using to update and elements innerHTML property and the addition of an ordered queue. The ordered queue makes your AJAX requests return to the client in the same order they were sent. One of the biggest area’s this comes into play is when creating livesearch implementations or any other time you’re making lots of AJAX requests and overwriting the results of the earlier ones with the results of latter ones.

More details (including a place to put testing results for your browser of choice) are available in the release notes on the HTML_AJAX wiki.

I’d also like to thank Laurent Yaish for helping with the testing of this release and Arpad Ray for working with me until we got the optimal implementation of setInnerHTML.

PHP AJAX File Upload Progress Meter Updates

Tuesday, March 14th, 2006

Over the weekend my file upload progress meter code got lots of traffic. It seems it made it made it on the del.icio.us popular list as well as getting over a thousands diggs. To celebrate this i’ve updated the code.

The main new feature is giving you feedback without having to patch PHP. Now the patched version gives you more information such as upload speed and estimated time to completion. But we still provide some nice user feedback even without it now.

I also created some wiki pages to start the documentation process.

So here are the demo’s

With the patch and extension
Without the patch

To get upload speed you will need to download and install the PHP Upload Progress Patch and extension.

If you want to use the code you need to:
Install HTML_AJAX (pear install HTML_AJAX-alpha)
Download PAFUPMU and install it somewhere accessible.
Add the code to your page using demo.php as an example.

The basic way the code works is we take a form containing a file upload and submit it using a hidden iframe as a target. Doing this lets the upload happen in the background. Then we poll the server on a regular basis (say a 2 second interval) asking it for update status. If you have the patch+extension installed this gives you file upload speed etc. If you don’t have the extesion we stop making AJAX calls and just animate the status bar until the upload finishes in the iframe and tells us were done.

In demo.php we handle generating the current page and handling the upload in the same page. So we start by handling the update.

<?php

include ‘UploadProgressMeter.class.php’;

$fileWidget = new UploadProgressMeter();

if ($fileWidget->uploadComplete()) {
        // output javascript to the iframe to send a final status to the main window
        // this will catch error conditions
        echo $fileWidget->finalStatus();

        // move the file(s) where they need to go

        exit;
}
?>

?>

This code only runs when your uploading so you’ll never see the output of it. This can make debugging problematic. One way around this is too hack the UploadProgressMeter to make the iframe non hidden.

Next you setup the JavaScript needed, first HTML_AJAX and then the uploaders JS.


        <script type=’text/javascript’ src=’demoserver.php?client=main,request,httpclient,dispatcher,json,util’></script>
        <script type=’text/javascript’ src=’demoserver.php?stub=UploadProgressMeterStatus’></script>
        < ?php echo $fileWidget->renderIncludeJs(); ?>

demoserver.php is included in the source, you might want to name it something else if you actually use this code. Its just a page using HTML_AJAX_Server to register the UploadProgressMeterStatus class

You also need some CSS to style the progress bar. The only important thing is that .progressBar and .progressBar .bar are relatively positioned.


.progressBar {
                position: relative;
                padding: 2px;
                width: 300px;
                height: 40px;
                font-size: 14px;
        }
        .progressBar .background {
                border: solid 1px black;
                width: 270px;
                height: 20px;
        }
        .progressBar .bar {
                position: relative;
                background-color: blue;
                width: 0px;
                height: 20px;
        }

Finally you finish things up by building a form. Note that you can include other elements in the form, but if they need to produce output you’ll have to manage calling back into the parent page from the iframes output.


<form action="demo.php" enctype="multipart/form-data" method="post" <?php echo $fileWidget->renderFormExtra(); ?>>
< ?php echo $fileWidget->renderHidden(); ?>

<label>Select File: </label>
<div>
< ?php echo $fileWidget->render(); ?>
< ?php echo $fileWidget->renderProgressBar(); ?>
</div>
</form>

AJAX and Latency

Monday, February 13th, 2006

So i just saw a great piece by Harry Fuecks on how latency can effect AJAX requests. Its one of his demo’s from the ajax@localhost presentation he gave at the PHP Conference Uk.

Now this showed a number of interesting problems, and while HTML_AJAX does a bit better then some toolkits it doesn’t handle them all. However thanks to HTML_AJAX’s design it not that hard to work around some of them.

So to that extent here is a really simple livesearch demo that keeps the reponses in the same order as the requests. The server is adding latency for you so you don’t need to worry about setting up a proxy to try it out. This is only available from HTML_AJAX svn right now, but we should do a release in another week or so there are lots of other good fixes in it.

Please note this queue isn’t really all that great for livesearch (ie it pounds your server). The current queue that is recommened for livesearch (and the one that HTML_Quickform_Livesearch (demo on my server, not the final version) uses sends a request at a maximum rate of every 350ms (this rate is configurable) instead of per character typed.

Finally this is just a quick hack, if you set the latency up too about 10 seconds you’ll start hitting some bug in the timeout code. The timeout is getting combined amoung multiple elements or something. The JS code might be really leak happy too, the queue doesn’t actually have all that much control of what happens when a request is complete just in when it sent in the current design. So to get around this i replace the users callback with one in the queue, and then do some closure fun. And here is the new queue code if you want to take a look.

HTML FAQ Answer: Other library integration plans

Tuesday, February 7th, 2006

I answered an FAQ question tonight on the HTML_AJAX wiki, im posting the answer here as well since I know most people don’t check the wiki for changes every day.

Outside of this answer I’d like to hear from what other libraries people would like too see integrated with HTML_AJAX and the reasons for this.

Question:
Will HTML_AJAX integrate with other Javascript AJAX libraries such as scriptaculous? How would this integration look like?

HTML_AJAX doesn’t have specific plans to integrate with other JavaScript libraries. Part of this is because external dependencies make for a more complicated installation process. It might make sense to offer some optional dependencies on a library like scriptaculous automatically using its visual effects for the loading box or something, but there isn’t a lot to gain from making default visuals like that flashier since they are designed to be easily replaceable.

Most integration would take place in higher level components. Its unclear weather higher level components like that should be part of HTML_AJAX delivered through PEAR or if they should just be supported by HTML_AJAX and made available from http://htmlajax.org or some other site. If your interested in building widgets or components based on HTML_AJAX please let me know.

HTML_AJAX does however offer the ability to use its library loading mechanism with any JavaScript library. I use scriptaculous in conjunction with HTML_AJAX and I load both libraries through the server.

To do this you just need to register the library with your server and load add its flag to your include line.

PHP code

<?php

$this->server->registerJSLibrary(’scriptaculous’,
    array(‘prototype.js’,’scriptaculous.js’,‘builder.js’,‘effects.js’,‘dragdrop.js’,‘controls.js’,’slider.js’),‘/pathto/scriptaculous/’);

?>

HTML


<script type="text/javascrpt" src="server.php?client=scriptaculous"></script>

PHPMagazine.net Interview

Thursday, February 2nd, 2006

I did an email interview with PHP Magazine.

Its mainly about HTML_AJAX but there were also some general AJAX questions and questions about PEAR. Responding to an interview like that takes a lot longer then I thought. Anyhow if your interested in the future plans of HTML_AJAX check it out.

HTML_AJAX 0.3.4 is released

Tuesday, January 31st, 2006

HTML_AJAX 0.3.4 was released today, it contains lots of bug fixes so if you use HTML_AJAX you’ll want to upgrade.

Release notes and testing results are available on the wiki, and the examples are available online if you want to see some of the basic features.

I’m hoping to do a beta release soon, so if you have time to help with an API review please get a hold of me.

HTML_AJAX Feature of the Week: Javascript Behaviors

Tuesday, January 24th, 2006

I’m trying out something new here, every week i’m going to write a short post describing an HTML_AJAX feature. Hopefully this will get some people started using the new features and maybe even get some more developers helping out with the project. It will also give me a place to try out some material for my upcoming AJAX book.

JavaScript Behaviors

JavaScript Behaviors are pieces of JavaScript code applied to DOM elements through the use of CSS selectors.

HTML_AJAX ships with a slightly modified version of the Behaviour javascript library. The slight modification is the replacement of the css parsing/selecting code with Dean Edwards cssQuery() library. This was done for a couple reasons, first the css code in behavior is under an unknown license and Dean’s code supports more of the css selector including most of css3.

I also used the American spelling of Behavior instead of the British (darn extra u’s)

Turning Behaviors on

Assuming you already have HTML_AJAX installed all you need to use behaviors is add “behavior” to your list of libraries.

If you just wanted the behavior library you could do:


<script type="text/javascript" src="server.php?client=behavior"></script>

Or including it with some of the other HTML_AJAX pieces


<script type="text/javascript" src="server.php?client=util,main,request,httpclient,behavior"></script>

Adding Behavior Rules

In most cases you’ll want to put your behaviors in their own JavaScript file, that way they can be reused and they don’t clutter up the html, thats the point of them after all. But you can just toss them in a script block in any file.

An example rule is shown below:


Behavior.register(
        "h1",
        function(element) {
                element.style.color = ‘blue’;
        }
);

Now this rule is rather worthless since its just setting a style rule, something that css is much better suited for but it does show a couple important things. You have immediate access to the matching elements, this allows you to create new child elements, update properties including innerHTML, and set event handlers.

You can set event handlers using onEvent methods but i prefer to use a couple util methods in HTML_AJAX that map to setEvent etc.

A more useful example which submits all the forms on a page using AJAX is shown below:


Behavior.register(
        "form",
        function(element) {
                var handler = function(e) {
                        var target = HTML_AJAX_Util.eventTarget(e);
                        HTML_AJAX.formSubmit(target,target);

                        // cancel submission in IE
                        e.returnValue = false;
                        // cancel submission in FF
                        if (e.cancelable) {
                                e.preventDefault();
                        }
                }
                HTML_AJAX_Util.registerEvent(element,’submit’,handler);
        }
);

There isn’t a lot too see here, we build a function to handle the submit event. It submits the form using HTML_AJAX.formSubmit, the first param is the form to submit, the second is the element to update (The second element is optional but do a bug in 0.3.3 it not being set isn’t detected correctly so you’ll have to upgrade to 0.3.4 to skip it). Then we cancel the normal form submission.

Wrapping it up

These examples show some of the power of behaviors, but there really is a lot more that you can do with it. If you have any tips feel free to leave them on the wiki or as comments to this post.

Run the example.

View the full example Source.

Download the example code.

Looking for HTML_AJAX Success Stories

Thursday, December 8th, 2005

If you’ve used HTML_AJAX to make something cool I’d like to hear from you.

If what you’ve created is publically accessible that would be even better.

Just leave a comment on this post saying what you’ve created and given a link to it if you can. Any suggestions on improvements that would make further development easier are also appreciated.

HTML_AJAX 0.3.1 Released

Monday, December 5th, 2005

HTML_AJAX 0.3.1 is out, lots of good bug fixes, and iframe fallback support for Opera and IE with activeX turned off.

More details are available on the release notes on the wiki.

I would like to thank Elizabeth Smith for all her testing and bug fixing in this release.

Feature wise were getting close to beta release, its mainly getting a browser compatability test suite added in and doing some basic API review. If you have experience supporting an API without breaking bc, it would be great to get your feedback on HTML_AJAX.

This circle expands additional navigation
You should really buy my AJAX book.
You'll learn not only the technology you need for implementation but also an understanding that will help you get the most from AJAX.
You'll also have my eternal thanks :-)