Add this blog to Del.icio.us, Digg or Furl | Create Watchlist for this blog

Archive for the ‘programming’ Category

ajax script tutorial - quick technology intro

Wednesday, June 20th, 2007

I love short stories to get started in a new technology. So here is one about ajax - the current hype on web platforms.

What is it for

Send requests asynchronous to your webserver and process the results within the current client-page-DOM without re-loading the whole page!

If you need special data in your webpage as response to a user action then use ajax. It is not meant for a whole Web GUI. If you use ajax for too much user navigation you will explore the two major drawbacks soon: The user can’t use the browser’s back button and search engines will ignore you (well, there are workarounds but those are bad browser dependent hacks).
The typical situation where ajax is useful is when you have two drop-down lists and the content of the second list depends on the selected entry of the first. I.e. “choose your cpu:” - first list contains manufacturers “Intel”, “AMD”, “IBM”, “Motorola”, second list contains processor model.

Technology, Syntax, Objects

On client side your users need a javascript enabled webbrowser of a “newer” generation. On server side you need nothing special, just use your favorite technique (there’s more importance on the selected protocol format - like just string or xml or json). On webdesigner’s side you need some DHTML and javascript.

A typical javascript function that initiates an ajax call with an url as parameter looks like this:

var request = false;  // you need this variable globally 

function initiateAjaxCall(url)
{
  request  = new XMLHttpRequest();
  request.open("get", url, true);
  request.onreadystatechange = async_event;
  request.send(NULL);
}

Where the XMLHttpRequest is the javascript-ajax object to focus on (for IE6 you need some workarounds well known in the web). ajax is “Asynchronous Javascript and XML” so it’s asynchronous and so you need a callback function (a function that gets called when an event occurs). Above “async_event” is declared to be your event handling function to handle the webserver’s asynchronous response.

There are four events your callback will be called with:

ajax state table:

0 = uninitialized
1 = loading
2 = loaded
3 = interactiv
4 = complete

For this quick intro, only state 4 is of interest. Maybe I’ll get back on this later in another post (can program nice progress bars with this infos).
Your event handler could look like this:

function async_event() {
  switch(request.readyState) {
  case 4:
    if (request.status != 200) {
      alert("HTTP Response not OK : Code:"+request.status);
    } else {
      myProcessing(request.responseText);
    }
  break;
  default:  break;
  }
}

In the “myProcessing” function the final response processing is done (usualy it’s any DHTML manipulation of the current DOM).

Full Code Example
It’s not that easy to invent a simple example that makes at least little sense, so don’t be to critical with this.

ajax script tutorial - example 1
Initial view of the example

To show up the technology in short code we build a website that displays the current client time (javascript) and a button to request the current server time. When the button is pressed, the current server time get’s fetched from the server by magical AJAX and is finally display via a DOM manipulation in - again - javascript.

We start with the server side (in php - to keep it simple)
File getTime.php

<?php echo date("H:i:s"); ?>

That was pretty simple, now we do the html page that uses ajax:
File getTime.html


<html>
<head><title>AJAX Test 1</title>
<script type="text/javascript">
   <!--
   // our global request variable
   var request = false; 

   // function to initiate the ajax call
   function initiateAjaxCall(url)
   {
     request  = new XMLHttpRequest();
     request.open("get", url, true);
     request.onreadystatechange = async_event;
     request.send(null);
   }

   // ajax callback function
   function async_event() {
     switch(request.readyState) {
     case 4:
       if (request.status != 200) {
         myProc("Error Response Code: "+request.status);
       } else {
         myProc(request.responseText);
       }
     break;
     default:  break;
     }
   }

   // function to print the ajax result
   function myProc(text) {
      var now = new Date();
      var ct = document.getElementById("CTIME");
      var st = document.getElementById("STIME");
      ct.innerHTML = ""+now.getHours()+":"+
                               now.getMinutes()+":"+
                               now.getSeconds();
      st.innerHTML = text;
   }
   //-->
</script>
</head>
<body onLoad="myProc('---');">
   <h1>Ajax Test 1</h1>
   Client Time: <span id="CTIME"></span><br>
   Server Time: <span id="STIME"></span>
   <br><br>
   <input type="submit" value="fetch server time via ajax now"
                          onClick="initiateAjaxCall('getTime.php');">
</body>
</html>

ajax script tutorial - example 2
After pressing the button, server’s time is displayed

Multithreaded programming in D

Friday, June 8th, 2007

While in C++ there was no build-in threading support, D comes with a JAVA-like class “Thread”. So while in C/C++ you had to mingle around with threading libs like pthread or solaris-threads, in D you can leave that problem to phobos.

A simple example shows all the simplicity:

import std.c.time;
import std.stdio;
import std.thread;

int runThread(void *ptr)
{
  printf("Thread %d startedn", cast(int)ptr);
  sleep(10);
  printf("Thread %d endedn", cast(int)ptr);
  return 0;
}

int main()
{
  Thread t1 = new Thread(&runThread, cast(void *)1);
  t1.start();
  sleep(2);
  Thread t2 = new Thread(&runThread, cast(void *)2);
  t2.start();

  while ((t1.getState() == std.thread.Thread.TS.RUNNING)
            || (t2.getState() == std.thread.Thread.TS.RUNNING))
    Thread.yield ();   

  printf("program readyn");
  return 0;
}

That’s it. Save the code as ThreadTest.d, than compile with “gdc ThreadTest.d” and run a.out (or a.exe). What you get as output should be very similar to:

rainer@ThinkTop ~
$ ./a.exe
Thread 1 started
Thread 2 started
Thread 1 ended
Thread 2 ended
program ready

Programming in D - getting startet

Sunday, June 3rd, 2007

I am programming in C/C++ for more then 15 years now. I took a look at JAVA, programmed some applications for 5 years now. But I am not so enthusiastic with JAVA, I find it kind of childish - it never stepped out of that web application area (in my opinion). No question, JAVA is bad for system programming - and no question too, there are some better choices today for business legacy system than JAVA.
I think the programming world is moving to the component side (away from the one-for-all approach, but independent from the infrastructure system for now). So what I looked for is a modern language to program fast, system-near components. And I found D.

If you search for information D is a terrible name
Try “D” in google and you will get some billions of results. Too bad, we need a web-catalog for this topic, but start with wikipedia for a first try. You will find that …

D is imperative, object-oriented, and metaprogramming
In short, that means that D knows objects and templates.

Continue with “Hello World”
The usual hello world is pretty simple and pretty close to C:

import std.stdio; // writefln() needs this module
int main(char[][] args)
{
writefln("Hello World!");
}

As you see, the include “stdio.h” has been replaced by a import std.stdio (looks like we have a package-like concept here now). And the printf() is writefln() today.

But you need a D compiler now
So start with the dgcc project. They deliver for all major (and some minor) plattforms. Install the compiler, save the code from above as test.d then compile like “gdc test.d”. As result you get the well known a.out executable (or a.exe under windows).
Run a.out and you will get:

Hello World!
Error: AssertError Failure test.d(5)

That’s because you didn’t return from your main function, so D is more severe than C. Insert a return 0; after the writefln() line and you’re done.

Next post will start with a serious application: A TCP/IP server in D.