Head First AJAX

Posted by Dan | Posted in JavaScript | Posted on 12-07-2009

2

Currently reading a great AJAX book, Head First AJAX, by Rebecca Riordan. I was a little skeptical at first by the format of these “Head First” books. I had heard so much about these books that I decided to give it a shot. I have to say I’m very pleased. It makes the material very easy to understand, and I certainly need a good book to review my AJAX.

So what is AJAX?

At its core, AJAX is just making a part of the page do something else while not refreshing the entire page. So for example, you can press a button, and just the button alone would load data from the server and display it on another part of the page (maybe right above it) while not loading the entire page. This is benefit one. It uses the JavaScript XmlHttpRequest (XHR) object .

Benefit two, is that with that XHR object, you can make HTTP requests that traditional HTML pages cannot. An HTML page can make a GET or POST request (e.g. via a form). With an XHR object, you have all HTTP request methods available.

When AJAX first came out, it used just XML – the server side script (e.g. ASP page) would generate XML data and the XHR object would retrieve it. Now, you can use JSON (a native JavaScript data structure) or any form of data structure you want. So the “X” in AJAX really is any type of data structure you want to pass the data from the ASP page to the XHR object.

Some JavaScript frameworks make AJAX extremely easy to use. jQuery can make a GET request using one line of code (compared to the many in the example code from my site). Also, jQuery is part of the .NET framework (last I heard MS announcing it) and should be integrated into Visual Studio.NET.

Here’s a great snippet that bundles the logic to return an XmlHttpRequest object if the browser can in fact create the object. I find it quiet useful.

function createRequest() {
  try {
    request = new XMLHttpRequest();
  } catch (tryMS) {
    try {
      request = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (otherMS) {
      try {
        request = new ActiveXObject("Microsoft.XMLHTTP");
      } catch (failed) {
        request = null;
      }
    }
  }	
  return request;
}

Some additional code, wrapped in functions, that sends the request object to the server, and fires the showUsernameStatus function. This is grabbed from the book site. Posting it here for my own benefit.

window.onload = initPage;
 
function initPage() {
  document.getElementById("username").onblur = checkUsername;
  document.getElementById("register").disabled = true;
}
 
function checkUsername() {
  document.getElementById("username").className = "thinking";
  request = createRequest();
  if (request == null)
    alert("Unable to create request");
  else {
    var theName = document.getElementById("username").value;
    var username = escape(theName);
    var url= "checkName.php?username=" + username;
    request.onreadystatechange = showUsernameStatus;
    request.open("GET", url, true);
    request.send(null);
  }
}
 
function showUsernameStatus() {
  if (request.readyState == 4) {
    if (request.status == 200) {
      if (request.responseText == "okay") {
        document.getElementById("username").className = "approved";
        document.getElementById("register").disabled = false;
      } else {
        document.getElementById("username").className = "denied";
        document.getElementById("username").focus();
        document.getElementById("username").select();
        document.getElementById("register").disabled = true;
      }
    }
  }
}

Here’s a simple way to read a text file (data.txt), barebones, on Firefox, without checking if XMLHttpRequest object exists or not.

<html>
<head>
<script language="JavaScript">  
ajax = new XMLHttpRequest();
 
function ShowData()
{  
  ajax.open( "GET", "data.txt", true );  
  ajax.onreadystatechange = function() 
  {
    if ( ajax.readyState == 4 ) 
    {      
      document.getElementById("DataPanel").innerHTML = ajax.responseText;
    }
  }    
  ajax.send(null);
}  
</script>
 
<title>hey!</title>
</head>
<body>
  <button onclick="ShowData()">Show Data</button>   
  <div id="DataPanel"></div>  
</body>
</html>

This is data.txt, which is in the same directory as the html page above:

05/12/2009  10:32 PM             1,024 .rnd
10/03/2009  12:55 AM               428 1.txt
05/11/2009  10:37 PM                 0 AUTOEXEC.BAT
09/29/2009  09:56 PM             5,256 bar.emf
05/11/2009  10:37 PM                 0 CONFIG.SYS
12/06/2009  12:43 AM    <DIR>          Dan
12/06/2009  12:45 AM                 0 data.txt
05/11/2009  11:00 PM    <DIR>          DELL
05/11/2009  10:40 PM    <DIR>          Documents and Settings
05/11/2009  11:28 PM    <DIR>          Intel
11/24/2009  11:53 PM    <DIR>          Program Files
07/18/2009  12:21 AM    <DIR>          temp
11/24/2009  11:57 PM    <DIR>          WINDOWS

I’ve Switched to Python from Perl

Posted by Dan | Posted in Perl, Python | Posted on 12-07-2009

0

So I’ve finally dumped Perl for my systems scripts. Partly was for maintainability. Overall, when doing some benchmarks myself, it seems that Perl beats Python in simple text parsing and file manipulation, which is most of the time is what I use it for. Ugh. I do find it though, that in most teams, Perl can be cryptic and unnecessarily harder for one to jump into. Python solves this. I think Python (after playing around with it for about a week) is a much more elegant language. Python will be a great addition to my toolkit for system automation. Much easier to apply OOP principles and write readable code. It’s a pleasure to write in this language and I look forward to learning more about it.

Also, while searching for performance tests on which language was “faster,” I ran across this site: The Great Win32 Computer Language Shootout . Of course, not to be used as a definitive guide, it does serve as a baseline, I think, for very simplistic tasks in a language.

On a related note, here’s a great video I saw on “Python in the Enterprise – How to Get Permission”:

If you start your own company or run your own project you can usually choose the programming language, but if you work for a large company there are probably architects and others who keep a tight rein on approved technology. How do you steer a big ship towards dynamic programming languages, and how fast can it turn? Come hear the story of one software developer employee who in 20 months facilitated the adoption of Python as the standard scripting language for an enterprise with 25,000 employees. Leave with ideas for advancing dynamic programming languages in your workplace, and with hope that change is possible.

I looked into Ruby, and found various similarites. Python sold me due to its larger community and greater applications in the wild. I took a look at PHP for system scripting and it wasn’t fast enough for parsing large files. Lastly, I thought about JavaScript on the console via JSDB but then realized its breadth of native library functions wasn’t as wide as that of Python. I really love that Python is getting a lot of momentum from Google and Microsoft is doing more to support the IronPython (Python on .NET) platform.

Use PHP Functions in JavaScript

Posted by Dan | Posted in JavaScript, PHP | Posted on 10-15-2009

0

PHP.JS is a great JavaScript library that I don’t often see in overwhelming lists of JS Libraries out there. A few folks decided to port many PHP functions to JavaScript. Wicked cool! I suggest you take a look at what’s ported so far – there’s a whole bunch. Definitely check it out!

Google Code Playground

Posted by Dan | Posted in Development, JavaScript | Posted on 10-11-2009

2

Don’t know how long Google Code Playground has been around, but it’s a mini-editor that will let you code in JavaScript (with color coding!), interpret it on a bottom panel, and even show you results from various Google API snippets. Awesome tool.


code-playground

JSDB from Aptana Studio

Posted by Dan | Posted in Development, JavaScript | Posted on 10-09-2009

0

Aptana Studio is a great free IDE for JavaScript. By default, you can use the its Jaxer engine to interpret your JavaScript code. However, if you prefer to use JSDB, a more console-oriented interpreted based on Mozilla SpiderMonkey, keep reading. This will set you up so that from Aptana Studio, you can write JS code, and interpret it by hitting F5 and seeing results in the bottom panel.

1. Select External Tools

1

2. Enter the following in the textboxes:

2

Make sure the path to your project doesn’t have spaces! (bug with Eclipse)

3. Set the hotkey to F5 so it runs the external tool:

3

JavaScript for the Windows Command Console

Posted by Dan | Posted in Automation / Scripting, Databases, JavaScript, Systems | Posted on 09-26-2009

0

JSDB is a great JavaScript interpreter based on Mozilla’s Spidermonkey JavaScript engine. If you like working off the command console, I suggest you give it a go. Of course, not everything is supported, as there is no HTML/DOM context in the console. To compensate for it, the author of this tool has added some great features, like being able to connect to databases, use includes ( easily via the load(“file.js”) function ), and other network facilities, like fetching HTML content from other websites.

jQuery JavaScript Encryption

Posted by Dan | Posted in JavaScript | Posted on 09-20-2009

0

jcryption

This is a neat way to encrypt form fields on the fly when submitting. Good way to add another layer of security. This is a jQuery plugin that uses the public-key algorithm of RSA.

NES Emulator in JavaScript

Posted by Dan | Posted in JavaScript | Posted on 09-18-2009

0

super-mario-bros-duck-hunt-u-_001

This is pretty impressive. It’s an emulator in JavaScript. I’ll have to see how many instructions get run through the profiler and how it reads the binary ROM file (perhaps it was converted beforehand).