Simple jQuery AJAX w/ ColdFusion

I had a request to supply a sample HTML page that would send a subscriber’s email address to ColdFusion without reloading the page. So I figured I’d post it here for any others looking for a simple example. This method uses jQuery, AJAX and a ColdFusion component.

index.html or index.cfm

<!DOCTYPE html>
<html>
	<head>
	</head>
	<body>
		<div id="subscribeContainer">
			<input type="email"><button type="button">Subscribe</button>
		</div>
		<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>

		<script>
			(function($) {
				// bind the button with an event handler
				$('#subscribeContainer button').click( function(e) {
					// when button is pushed, POST data to remote ColdFusion component method
					$.post(
						'subscription.cfc',
						{
							method: 'subscribe',
							email: $('#subscribeContainer input').val()
						}
						)
						.done( function() {
							// everything worked
							$('#subscribeContainer').text('You have been subscribed.');
						})
						.fail( function() {
							// something failed
							$('
<span>There was an error subscribing.</span>').appendTo('#subscribeContainer');
						}
					);
				});
			})(jQuery);
		</script>
	</body>
</html>

subscription.cfc

component {

	remote void function subscribe( required string email ) {
		// call database insert method here
	}

}

Faux File Upload Input

The element <input type=”file”> is very ugly in most browsers and it seems that even Bootstrap didn’t put any effort into sprucing it up.

My end objective was to have a user press a rectangle box with a title inside which would open a file dialog and ultimately upload that file.

At first I thought this would be easy after some quick research in Google land. Not so.

Note: I’m using the jQuery 2.x library in my examples

<style>
	input {
		display:none;
	}
</style>

<form method="post" enctype="multipart/form-data">
	<div id="wrapper">click here to upload<br><br>
		<input type="file">
	</div>
</form>

<script>
	$('#wrapper').click(function(event){
    	$(':file').click();
	});
	
	$(':file').change( function() {
		$('form').submit();
	});
</script>

At first I thought it would be as easy as 1) hiding the input 2) watching the click event on the container 3) trigger the input’s click event and 4) submit the form.

But what I found out was that the event listener kept firing infinitely until the browser aborted with a “Uncaught RangeError: Maximum call stack size exceeded” error in the console. Though honestly I don’t completely understand what’s going on here, the click event by my mouse bubbles up to the child input element.

To resolve that issue I started looking for the event that was not fired by the input element:

<script>
	$('#wrapper').click(function(event){
		if( !$(event.target).is(':file') ) {
	    	$(':file').click();
	    }
	});
	
	$(':file').change( function() {
		$('form').submit();
	});
</script>

At this point @chrish on CFML Slack was helping me out and also offered up a solution were as now we are stopping propagation for the input element.

<script>
	$('#wrapper > :file').click(function(event) { event.stopPropagation(); });
	$('#wrapper').click(function(event){
    	$(':file').click();
    }
	
	$(':file').change( function() {
		$('form').submit();
	});
</script>

I ended up sticking with the first solution incorporating the “if” statement until Jessica Kennedy reminded me of a simple solution using the label element. Because this simplifies things (AKA less likely to break) I’m now sticking with this solution. Normally a label will focus on the input field when clicked on. But in this case it fires off an event to open the file dialog. I’ve tested this in Chrome, FireFox and IE 9+. I’m pretty sure the label element has some limitations what you can stick in it, so this may not always work for you. But in my case I was able to apply the Bootstrap widget classes (not seen in this example) and it worked as expected.

<style>
	input {
		display:none;
	}
</style>

<form method="post" enctype="multipart/form-data">
	<label id="wrapper">click here to upload<br><br>
		<input type="file">
	</label>
</form>

<script>
	$(':file').change( function() {
		$('form').submit();
	});
</script>

#file, #html, #upload

jQuery UI Dialog Centering Issue

I’m working with some code that’s been worked over many, many times over the years. It could a thorough scrubbing, but that’s not in the scope of my request.

I just upgraded the jQuery UI to version 1.9.2 and jQuery to 1.8.3 and added a simple dialog.

test_dialogIt was expected that the dialog would center itself to the browser window. However it appeared to be centering itself to the html element and scrolling the page to make it centered if the content was longer than the window height.

Here’s the code:

<html>
<head>
    <title>My Title</title>
</head>
<body>
    <div id="userNoticeDialog" style="display: none;" title="Notice">
        test content
    </div>

    <script type="text/javascript">
        $("#userNoticeDialog").dialog();
    </script>
</body>
</html>

After a process of elimination and seeing that there was no doctype declared, I tried adding a doctype. That resolved the issue.

<!DOCTYPE html>
<html>
<head>
    <title>My Title</title>
</head>
<body>
    <div id="userNoticeDialog" style="display: none;" title="Notice">
        test content
    </div>

    <script type="text/javascript">
        $("#userNoticeDialog").dialog();
    </script>
</body>
</html>

I believe the reason was the lack of a DOCTYPE caused the (Chrome) browser to go into quirks mode, while the inclusion of the DOCTYPE caused the (Chrome) browser to go into standards mode. However, I’m not sure how to detect which mode the Chrome browser is currently in. Does anyone know?

#center, #dialog, #doctype, #html, #jquery, #ui

Simple HTML5

I keep going back to look and see what is actually required as a minimum for HTML5 markup, so I thought I’d blog it for easy reference.

The non-normative minimum markup for HTML5 is:

<!DOCTYPE html>
<html>
 <head>
  <title></title>
 </head>
 <body>
 </body>
</html>

Notes:

  • The DOCTYPE is required for legacy reasons. Including the DOCTYPE in a document ensures that the browser makes a best-effort attempt at following the relevant specifications.
  • HTML is not case sensitive
  • A closing slash is not needed for self-closing elements
  • A link element must have a rel attribute. If the type attribute is omitted on an external reference it will default to the MIME type of the file being referenced. For example if the href is “mycss.css”, the type will become “text/css”.
  • If no type is defined for the style element, then it defaults to “text/css”
  • If no type attribute is defined for the script element, then it default to “text/javascript”

#html5, #template

Understanding Hexadecimal Color Values

I’ve known about hexadecimal color values for HTML probably since 1994, back in Netscape Navigator Beta days. I’ve always known that they represent a group of Red-Blue-Green values, that when modified you get a new color, however slight or dramatic. Each position can have a value of 0,1,2,3,4,5,6,7,8,9,a,b,c,d,e or f.

But I never really understood why such a silly system that required me to open Photoshop or use Dreamweaver to find the color I’m looking for; that is until today.

Most of us humans do math with a base of 10 (1, 10, 100…). However computer binary code uses a base of 8 (8, 16, 32, 64, 128… look familiar from your SD memory cards?) Hexadecimal has a base of 16, which is easy for a computer to use since 8 + 8 = 16.

Also remember that most visible colors can be reproduced using a mixture of red, green or blue (primary colors) thus we have the RGB groupings.

So “000000” is black and “FFFFFF” is white. In otherwords “000000” has no color and “FFFFFF” has all the color. So what if you want just a little red? Something like “010000” should do it. But what if you want a lot of red? Try “FF0000”. Yellow? “Try “FFFF00”. But this is the basics most of us know.

But where does the alphabet come into play? Can’t seem to get that one position above 9 can you? So use the alphabet to keep adding on top of that 9. So the value of F basically equals a 15 fit into one placeholder. If you want to go to 16 you’d start back at 0 and add a 1 to the previous place holder thus “0F0000” becomes “100000” for that little bit of red.

If this explanation is boring you or just confusing – watch a great short video about this at Nettuts+ .

After I watched this video I now have a clear understanding of what is going on here instead of just winging it via an IDE.

CSS Equivalents for the pre Tag and nowrap Attribute

Rarely have I used the <pre> tag or the nowrap attribute in my code. However it is there, and I haven’t even considered if there was a CSS alternative. Today I ran into the CSS property for these that I’ve never seen before; the white-space property.

Example:

p {white-space: nowrap}

The possible values are:

normal

nowrap – same as the nowrap attribute

pre – same as the <pre> tag

pre-line – text wraps when necessary and on line breaks

pre-wrap – whitespace is preserved by the browser (same as &nbsp;) and text will wrap when necessary and on line breaks

inherit – ( not supported by IE, including version 8 )

For additional reference see https://developer.mozilla.org/en-US/docs/CSS/white-space

Google CDN Tips

Thanks to BrightMix for hosting the jQuery meetup presented by Jonathan Sharp last night in Omaha. Jonathan presented on the new features of jQuery 1.4 last night along other Q&A topics.

Lately I’ve been experimenting with the Google CDN for delivering jQuery and jQuery UI. The reasons behind using the CDN is faster library loads, cross-internet library caching, automatic version management, and decreased hosting bandwidth. Jonathan offered a few tips:

  1. SSL works with the CDN’s path based requests. Use either “http://ajax.googleapis.com” or “https://ajax.googleapis.com”.
  2. For automatic switching between http:// and https:// get rid of it. Yep – just use “//ajax.googleapis.com”. Don’t confuse the slashes as “\\” will get you a network path. This should also work for “<img src=’//…” and “<a href=’//…” but I haven’t tested that yet.
  3. When using a path such as “//ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.js”, you can control the automatic versioning by increasing or decreasing the dot notation on the version. In the example above, I will always get the latest version of 1.4 – currently 1.4.1. If I wanted to always get 1.4.0, I would append the “.1”. If I always wanted to get the laster 1.x version, I’d remove the “.4”.