jQuery – An Overview

Yesterday my boss asked me about a simple overview/tutorial explaining jQuery, Bootstrap and some other web technologies, and how they work together. I decided to also post the result on my blog, so here is the first part. You may recognize some code from a previous blog entry.

jQuery is a currently very popular Javascript framework/library. There are other ones, like Dojo (used by IBM in XPages) and YUI (originally developed by Yahoo), but jQuery is right now at the top when it comes to usage.
jQuery contains the plumbing behind the scene, it contains functions to let the different elements on the page talk to each other and interact, for example trigger events on click or change. It also have functions to hide and show elements (either directly or fade in or out).

One of the big benefits with jQuery is that many functions are much easier to do than in traditional Javascript. It also addresses browser inconsistency, so you don’t have to write different code for Firefox and Internet Explorer. jQuery is Javascript, just packaged in a nice library and simplified. There are also UI components and mobile components, found in jQuery UI and jQuery Mobile. Here are a couple of examples, comparing plain Javascript with jQuery: http://blog.jbstrickler.com/2010/06/vanilla-javascript-vs-jquery/.

jQuery ties into the DOM (Document Object model) of the browser/webpage in a very easy-to-use way. The way elements are addressed is identical to how you do it in CSS, using . (dot) for classes and # for individual elements.

It is not hard to start with jQuery. You do not even have to host the library on your own server, several companies (including Microsoft and Google) host jQuery (as well as other libraries and frameworks) in what is called a CDN (Content Delivery Network). You simply include a line of code in the head section of your HTML, telling the browser to load jQuery from a specified location, and you are all set:

<head>
    <title>Hello, jQuery</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
</head>

Notice that you don’t use http: or https: at the start of the URL. This is a trick that makes it work both on a http or a https site. However, if you have the code locally in the file system on your computer (like many do before uploading the html file to a server), you must add http: at the beginning for it to load.

Let take a look at our first jQuery example. Below we have a very simple piece of HTML code:

<body>
    <button id="btnSave">Save</button>
    <div id="messageBox"></div>
</body>

What we want to do is that when the button is clicked, a message should be displayed in the div with ID messageBox. That is done with the following piece of jQuery:

$("#btnSave").click( function() { 
    $("#messageBox").html("You clicked the Save button."); 
});

What this do is to replace everything inside the div with the text/HTML code we specify. The second line is the code to execute when the event specified triggers/fires. You can put triggers on almost any element, and depending on the element type, you have different triggers.

The code between the first and last curly brackets { } is being executed when the event is triggered. As you can see, I have the code I showed earlier nested inside this code. What all this does is to wait until the page is loaded, then start creating event triggers.

There are two schools when it comes to where you put the jQuery code. Soem developers prefer to put the code inside <script> tags at the end of the page, after all HTML code and right before </body>. That is is so that the code is not executed until the page (and all the elements on it) have been loaded.

There is another way to do it, as well. This one allows you to put the code in the <script> section of the header section, but it us using jQuery to not load any code until the page has finished loading:

$(document).ready(function () {
    // Setup the element with id "btnSave" to react on click
    $("#btnSave").click( function() {
        // When clicked, set the innerHTML of the element with
        // id "messageBox" to the specified html string.
        $("#messageBox").html("You clicked the Save button.");
    });
});

The important thing is that you can not start put events on elements until they have been created on the page, or nothing will work.

One of the really cool features with jQuery is how easy it is to call another page/url and get something back. This is commonly called Ajax (Asynchronous Javascript and XML), even if it these days more often than not involves getting JSON back instead of XML.
JSON stands for Javascript Object Notation and is a way to package data in the same way you would do if you created a Javascript object. A simple example would look like this:

{
    "FirstName":"Karl-Henry",
    "LastName":"Martinsson",
    "Department:"IT"
}

I can now assign the object to a variable (let’s call it employee) and I can then access the values using regular Javascript:

alert(employee.FirstName + " " + employee.LastName + " works in " + employee.Department);

This ease of parsing makes JSON ideal to use to retrieve values from a data source and display them on a webpage, using Javascript.

Let’s look at a more complicated example. I will call a URL on a server, which will trigger an agent to run to retrieve data from a database and return it in HTML format. This particular URL points to a Domino agent written in Lotusscript, but it could be written in any language supported by the server, like php. For a Domino server, you could also use an XPages agent.

Here is the Javascript code to call a URL and put the content returned into a element on the web page:

function loadProgressNotes(clientunid) {
    $.ajax({
        url: "/mydatabase.nsf/GetProgressNotes?OpenAgent",
        data: {"ClientUNID":clientunid,"Start":"1","Count":"10"},
        cache: false
    }).done(function(returndata) {
        $("#progressNotes").html(returndata);
    });
}

I broke this code out as a separate function, as I need/want to call it in several places. The function just contains one single jQuery function call, .ajax(). I pass a Javascript object to the function, containing the data needed by the function. Many jQuery functions works like this, you pass a Javascript object with arguments instead of passing a large number of individual arguments. You can do the same in Lotusscript, by passing an object or a custom data type to a function instead of numerous arguments.

In this particular case, I am calling .ajax() with 3 arguments. The first one is the URL to go to, the second one is the data to send to that URL, and the last one is a flag telling jQuery to add a cache buster to the end of the URL it constructs. If I would not add that, and I had recently made the same call, I would get old data, as web servers and browsers cache data for performance reasons.
The interesting thing in the code above is perhaps that the data I pass to the URL are itself a Javascript object, so we have a Javascript object where one of the elements is another object.

So what happens is that jQuery performs a call to www.domain.com/mydatabase.nsf/GetProgressNotes?OpenAgent&ClientUNID=something&Start=1&Count=10&_15614312653

The last number is the cache buster, simply a timestamp (milliseconds since midnight, Jan 1, 1970).
The program/agent on the server reads the arguments, performs whatever database lookup it needs, and generates HTML based on that. This HTML is returned by the .ajax() call in data above. The jQuery call is sitting in the background and waiting for the agent to return the data. When this is done, the .done() event is triggered.
In that event, I have written some jQuery code to update the contents of the element called “progressNotes” with whatever the AJAX call returns, in this case some HTML.

It may be more common to have the agent return JSON and parse it, putting different values into different elements on the page. Here is an example, where I go through all the input fields and text area fields on a HTML form and collect the field values/contents for any of the fields having the custom attribute called notesfield. The value of the attribute is the field name in the Domino database, making it very easy to send the data to the correct place on the server.  A typical input field could look like this:

<input notesfield="FirstName" type="text" value="" placeholder="First Name">

Below is the Javascript code, using jQuery to update the record in the Domino database and return JSON that will indicate success or failure, as well as a custom message that will either explain the reason for failure or a message that the document was updated.

var json = new Object();

myjson["ClientUNID"] = "E7A2D820EE10123C86257BAD0056A5F4";

$('input[notesfield]').each(function() {
    fieldname = $(this).attr("notesfield");
    fieldvalue = $(this).val();
    myjson[fieldname] = fieldvalue;
});

$('textarea[notesfield]').each(function() {
    fieldname = $(this).attr("notesfield");
    fieldvalue = $(this).val();
    myjson[fieldname] = fieldvalue;
});

$.ajax({
    url: "/mydatabase.nsf/UpdateClient?OpenAgent", 
    data: myjson,
    cache: false
}).done(function(returndata) {
    if (returndata.status=="Error") {
        $(".errorMessageClient").html("Error! " + returndata.msg).show();
    } else if (returndata.status=="Success") {
        $(".successMessageClient").html("Success! " + returndata.msg).show();
    });
});

As you can see, it is easy to retrieve values from the JSON you get back.

That’s all for now. Next time I will talk about Bootstrap.

This Post Has One Comment

Leave a Reply