Category Archives: Javascript

Filling a select drop-down with ajax data using jQuery

In user interfaces, it’s sometimes the case, that you need to have dropdowns with content dynamically loaded from a database, and sure you can query the database and place the content in the HTML-source as regular markup, but you can also write a few lines of jQuery powered javascript, and provide the data from an ajax-source.

Here’s how to do it.

First make the drop-down and as the single option make a “loading” message – just to let the user know something is happening.

1
2
3
<select id="dropdown">
        <option value="-">-- loading --</option>
</select>

Next make a few lines of javascript, which runs once the page is ready, and let that initiate the json request (and fill out the drop down with the require values).

1
2
3
4
5
6
7
8
9
10
11
<script type="text/javascript">
$(document).ready(function() {
        $.getJSON("select_ajax.php",{}, function(data){
                       var options = '<option value="">-- select please --</option>';
                       for (var i = 0; i < data.length; i++) {
                                options += '<option value="' + data[i].value + '">' + data[i].label + '</option>';
                       }
                       $("select#dropdown").html(options);
        })
});
</script>

For convenience there’s a simple example available here. The example uses a static array as source, and in all practical uses this would probably be replaced by a database query.

Browser handling of broken includes in an Ajax world?

In this mordern web 2.0 age, javascript includes are used more and more – and in some cases solutions often depend on included content from 3rd parties. While it is nice these 3rd parties may provide us with data (such as the latest tweets from twitter), it would be quite nice, if issues on their server didn’t break the fancy page we’re building.

So the question is this: If you build a page and include javascript from foreign scripts, will error messages on their part break your site? We’ve made the assumption, that the Web2.0 page will degrade gracefully, so that the content/functionality of the javascript-includes is just extra frosting, not needed to use the page

We did a simple little test, and in the most common browsers, a server error (that is an errror signaled in the http-header status code), will just cause the browser to ignore the included content. If the header is a “200 Ok” header, the content will break.

The answer, no – assuming, that their servers provides a http-header, that signals error. If you have a few spare seconds, please visit the test page, and if your browser reports a javascript error, please leave you browser (make and model) and operating system in a comment below.

Building image tags with jquery

Like tables, jQuery also allows you to play around with all other tags. In a recent project, we wanted to change a fixed set of labels/texts into icons instead. For this challenge jQuery was used to build the new image tag, and for good measure, here is a small example of how you can build an image tag – including alt-text and click-event.

The basic code for building and inserting an image into the DOM looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
<div id="image"></div>
 
<script type="text/javascript">
$(document).ready(function() {
 
  $image = $('<img>').attr('src', 'image_polar.jpg');
  $image.attr('alt', 'Polar bear');
  $image.attr('height', '200').attr('width', '300');
  $image.click(function () { alert('You clicked the image'); });
  $image.appendTo('#image');
 
});
</script>

The code above creates a new image tag. Adds an alt-text and sets the height and width (resizing the image in the browser). Finally it attaches a click-event and inserts the image into the DIV-tag named “image”.

(se example)

jQuery and tables

I’ve been playing with jQuery the recent weeks, and while it is reasonable simple to get started with and the jQuery documentation is pretty good, I thought I’d share a few snippets of jquery examples/code, which showcases a few simple practical uses for jquery.

First up – tables and jquery.

With jQuery you can add content to a HTML table. Here are to simple examples on how to add content into a table.

First let’s see how you add a row with two cells to a table:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
 
<table id="tableOne" border="1">
 <thead>
  <tr><th>Col 1 </th><th>Col 2</th></tr>
</thead>
<tbody>
</tbody>
</table>
 
<script type="text/javascript">
$(document).ready(function() {
 
  $tableBody = $('#tableOne tbody');
 
  var $tableRow = $('<tr>');
  $('<td>').text('Row 1 Cell one').appendTo($tableRow);
  $('<td>').text('Row 1 Cell Two').appendTo($tableRow);
  $tableRow.appendTo($tableBody);
 
});
</script>

(se example).

Let’s build a slightly more advanced example and add data to a table from a javascript array.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<table id="tableOne" border="1">
 <thead>
  <tr><th>Table Header</th></tr>
</thead>
<tbody>
</tbody>
</table>
 
<script type="text/javascript">
var sampleData = new Array('One', 'Two', 'Three', 'Four');
 
$(document).ready(function() {
  $tableBody = $('#tableOne tbody');
 
  for (var row = 0; row <= sampleData.length-1; row++) {
    var $tableRow = $('<tr>');
    $('<td>').text(sampleData[row]).appendTo($tableRow);
    $tableRow.appendTo($tableBody);
  }
});
</script>

(see example).

Extending the second example and drawing the data populating the table from an ajax-source should be pretty simple. Have fun and enjoy jQuery.

Simple slideshow updated

Quite awhile ago I posted a little piece of javascript, which could be used to a (very) simple webpage slide show. Someone requested a version a little more advanced for use in a kiosk mode, and sure why not – updating the script with the option to set different times on the webpages displayed was a minor change, and it’s been done now.

If you’d like an updated version of a basic webpage slideshow with an option to specify the time each page is displayed, go ahead get it from the lab.

Cookie limits in browsers

How many cookies do you neeed and how many does the browsers support? – It seem to come up all to often, so after a bit of digging in search engines, here are (for my own convenience) the findings of what the limits are on cookies in the currently used browsers.

The cookie standard (RFC2965) specifies a browser should be able to handle at least 20 cookies per domain, but one thing is a standard – who does the real world look?

Internet Explorer

  • Version 6 supports 20 cookeis.
  • Version 7 supports 20 cookies – updated to 50 in an August ’07 patch.
  • Version 8 is supposed to support 50 cookies, but haven’t shipped at the time of writing.

Firefox

  • Firefox allws 50 cookies.

Opera

  • Allows 50 cookies.

Cheating (slightly – if you must)

Since it’s per domain (and remembering you can’t place cookies on the top level domain (.dk, .com or whatever) you can on many sites actually double the number of cookies available if you must. The key (or trick if you like) is to utilize the fact that most sites are located at www.example.com and you can place 20 cookies on example.com and another 20 on www.example.com.

Before doing this, do check with your server admin though, that requests to example.com is always redirected to the www-subdomain.

Selected Sources

Simple Webpage Slideshow

At work we produce a few websites and have a few “web dashboards”. Wouldn’t it be nice, if public screens around the office could play a little loop mixing the websites and the dashboards together in a slideshow loop?

After an hour of javascript debugging, a nice little generic webpage slideshow was put together, and if you have a similar need a copy is now available in the lab. It’s simple, it should work in most browsers, and it probably has the least features of any slideshow out there.

Changing a form submit url with javascript

Sometimes you might need to change the address a form submits to, it’s quite easy with javascript. One example could be if you – like me – from time to time is hit hard by comment-spammers. Changing the submit URL on the form with javascript, makes it at least somewhat harder for “automated brainless robots” to kill your site in a spam attack.

The recipie below is a very simple example, but so far it seems to work quite well:

<script type="text/javascript">
function doSubmit() {
  var target1 = 'hello';
  var target2 = 'world';
  var target3 = '.cgi';

  var supertarget = target0 + target1 + target2 + target3;
  var theForm=document.getElementById("theForm");
  theForm.action = supertarget;
  theForm.submit();
}
</script>

<form id="myForm" method="post" action="some_fake_address.php">
<input type="text" name="dummy field" value="">
<input type="button" onclick="javascript:doSubmit();">
</form>

Whats going on?

The form is a regular form except for to small things:

The action-url is a fake address. On the url it points to, is only an empty file (to prevent 404 errors in my errorlog.
The normal submit button has been changed to a regular button, and the onclick-evnt calls a small piece of javascript, which does the magic trick.

The javascript function can be more or less advanced depending on your needs. In this example it constructs the new target for the form submit by pasting three strings together and replacing the action of the form.

Don’t use Ajax blindly

GMail and other web applications have adopted a new technique coined Ajax (by Adaptive Path). It brings web applications a step away from the stateless web and closer to real applications. It’s harder to built applications with the applications, but it’s hot – and the most recent release of Rails (for Ruby) promises to make it much easier to do Ajax applications. Before you do too many Ajax applications, do think for a second.
Continue reading Don’t use Ajax blindly

Clientside sortable tables with memory

It’s been awhile since Stuart Langridge released some cool javascript which allows you t do client-side sorting of tables in an unobtrusive manner. Soon after Andy Edmonds released a merge with a function to made alternating row coloring he had made. Now Caspar has done a little magic and added (cookie) memory to the script – so it remember you most recent sort from visit to visit. The code is in my pre-alpha markup area.