Ajax Cookbook for the FHA Website

Ajax Cookbook for the FHA Website

Most users of the website have read the Bulletin Board (the most popular page on the site!) or looked up other residents’ (or their own) directory information. These two website facilities share a common technology that makes them fast and efficient. The technology is called AJAX – short for Asynchronous Javascript and XML. In brief, AJAX provides a way for a Javascript program to load a program on the web server and pass directive information to the program, then to retrieve the output from the program (which might be HTML, XML or JSON) and insert this output onto the page where the Javascript is running. Under normal circumstances, the time between the Javascript call and the appearance of the results of the call is measured in a few tenths of a second, or almost instananeously. This article will explain how that works, using a key “simplifier” Javascript function written for and widely used by our website.

 

All HTML entities (<p>, <input />, etc.) can have “attributes” specified within the angle rackets <> and after the entity identifier (p, input) in the form attr = ‘value’, where “attr” is some attribute, like “align” for paragraphs or “type” for input entities. Many entiries have event attributes, like “onclick” or “onkeyup”.  An event attribute specifies that some action should be taken when the event occurs, and the value of the attribute is a Javascript statement, most often, a call to a Javascript function. As a trivial example, the following would be perfectly legitimate on an HTML web page:

<p onclick=”alert(‘hello’)”>Click here to say ‘Hello'</p>

(Try it and see. Open jsfiddle.net and paste the above line into the “HTML” box, then click “Run” at the top of the page,then click the text “Click here to say ‘Hello'”. Use jsfiddle to try different Javascript constructions or interactions between HTML and Javascript.)

 A function in Javascript is a block of code which may optionally be given directives or data as “arguments” in a call to the function. The function does something, possibly depending on calling arguments, and may optionally return a value. A simple example:

function sum ( a, b )    // function’s name is “sum” and it accepts two arguments: “a” and “b”
{        // Beginning of function definition
  var c = a + b;    // declare (“var”) a new variable “c” and set its value to the sum of the values of arguments a and b
  return c;    // return the sum, stored in variable “c” as the function’s result
}        // End of the function definition
alert( sum ( 5 , 7 )); // What will this do? Use jsfiddle.net to check your answer.

NOTE: This has been the briefest of introductions to Javascript functions. You shoulld be reading w3schools’ Javascript tutorial and maybe studying a good tutorial text (e.g., “Eloquent Javascript“) to gain understanding and proficiency in Javascript.

On to the AJAX magic simplifying function mentioned above. The function is called doAJAX, naturally enough, and the source code id found at /code/doAjaxNEW.js.

To call doAJAX you need to know:

  1. The name and location of the PHP server file that’s going to execute your AJAX request, e.g., /code/runSQL.php
  2. The parameters (directives and/or data) needed by the server to perform your request, and
  3. The location (by HTML attribute “id” in an HTML entity, e.g., <div id=’ajax_data’>) where the server program’s output is to be saved.

 The name and location of the PHP server file: first, the location will usually be in the directory “/code”. The “/” says that the “code” director is relative to the website root: the server directory containing the website’s home page (in Joomla that’s a file named “index.php”) and the rest of the website. The choice of “/code” as the directory is because the stuff in “/code” is generally not PHP files embedded into Joomla articles, but are instead, supporting programs and functions called by the mbeded articles. PHP files directly embedded in Joomla articles are, in general, in the directory “/fhaphp”. (See the article “Building a Joomla Page With Custom PHP Code” if you don’t know what’s meant be “embedding files in a Joomla article.) In other words, “/fhaphp” files are the stars, and “/code” files are the support cast.

The name of the file is whatever the author chooses it to be. PHP files obviously need to have the extension “php” but the filename can be whatever is permitted in unix-land. (If you didn’t know already, our website server runs a unix variant called CentOS.)

So the program that delivers (serves) directory lookup requests to the browser has the location & filename “/code/dirServ.php”. Not so hard.

The parameters needed to fulfill the request: In your meanderings you may have encountered HTML Forms. If not, please go read about them now. Forms contain fields that can accept user inputs: <input type=’text’… /> or <input type=’checkbox’ … /> for example. These input fields in a Form on our website can be used to control a server program, but they must be passed to the server program somehow. Natively, inputs to a web program called by another web program can receive inputs in the form of a “querystring” or as “post” variables.

If you see a website URL something like

https://www.google.com/search?q=ajax&sourceid=chrome&ie=UTF-8

then everything after the “?” is called the “querystring”, and it’s just a string of “variable=value” pairs separated by “&”s. In the example, the variable “q” has value “ajax”, the variable “sourceid” has value “chrome”, and the variable “ie” has value “UTF-8”.

Querystrings are ok, in the sense that they’re supported on all browsers, but they’re limited in size and content (no bare “&”s, for example) and visible to the naked eye, so to speak (possibly a security exposure). Post variables, on the other hand are much less visible, and practically unlimited in what you can put into them. One way or another, the variables are made available to the called program (e.g., the AJAX server program) in a form called a “superglobal” in PHP. These are $_GET for querystrings and $_POST for post variables. (You know PHP variables like these are case sensitive, don’t you?) These superglobals are PHP associative arrays (simplified definiton: arrays indexed by names, not numbers). The index is the name of the variable, and the array element $_GET[‘variablename’] has the value of the corresponding querystring variable. $_POST[‘variablename’] would have the value of the corresponding post variable.

The called program knows how (querystring or post) its variables will be sent, and performs PHP operations to obtain, check, and use the expected variables. NOTE: Any variable data that’s going to be used in a database access must be “cleaned” before using it. Read up on “SQL Injection Attack” to see why.

Now we’ll see how to get parameters from the calling program to the server program using our doAJAX function. Prerequisite knowledge: Javascript Associative Arrays. To get the parameter names and their values from the Javascript environment which calls doAJAX to the PHP environment that actually used them, we define a Javascript associative array as follows (example taken from the rePaint function in the bulletin Board’s Javascript support /fhaphp/bb.js):

params = {
    debugging: 0,
    action: ‘repaint’,
    useremail: useremail,
    privUser: secode,
    daysago: daysago,
    search: srchTerm
};

This easy-to-understand Javascript statement defines an associative array “params” containing the elements:

params[‘debugging’]: 0;                 //    value is zero
params[‘action’]: ‘repaint’;            //    value is the string ‘repaint’
params[‘useremail’]: useremail          //    value is whatever is stored in the variable “useremail”
etc.

You will, I hope immediately grasp how easy is to write the parameter string and, formatted as it is (remember that Javascript ignores spaces outside of quotes, and newlines), how easy to see the array object’s variable subscripts and their values. That’s all there is to assembling a parameter list for a doAJAX call!

The location for the server’s output is a string constant (or variable containing a string constant) which identifies an HTML entity into which the server’s output will be stored once the server finished doing what the doAJAX function asks. This will almost always be an “id” attribute in a <div> element, but can be any uniquely identifiable HTML element that has the ability to contain HTML elements. Thus instead of a <div> element, one could specify the “id” of a <span>, a <p>, an <h3> or other HTML element that may, syntax-wise, include other HTML elements. WHen specifying an “id”, the string identifying the “id” should be prefixed with a “#” pound sign. THis identifies the string as an “id”, and nor a “class” or an HTML element name like “td”, “p”, ‘div”, etc.

In much of the FHA website’s code, if AJAX is used, a simple <div> is used to receive the server program’s output. Thus, in the main Bulletin Board program /fhaphp/bb.php you will see

<div id=’allPosts’>
</div>

and the call to doAJAX when the Bulletin Board is opened would be something like

doAJAX(‘/code/oldbbAdd.php’, params, ‘#allPosts’);

with three arguments: the server program name and location, the parameter list as described above, and a CSS-style selector identifying the “id” (the “#” says it’s an “id” and it’s value “allPosts”) into which all output from the server will be written. For the opening call by the Bulletin Board, the parameters say to retrieve the last five days of Bulletin Board posts, format them and write them into the <div> with id=’allPosts’. Dozens of logged-in users every day verify that that’s just what it does!

And that’s how to do AJAX using the AJAX cookbook for the FHA website.