My Blog

contains PHP and other web related content. (Sometimes there are some off topic things - don't freak out!)

Archive for the ‘jquery’ Category

How to handle AJAX errors with jQuery

Tuesday, August 24th, 2010

Many times, the ‘error’ property of the jQuery AJAX call is ignored. Most often, you’ll see just references to the success portion.

The error attribute of the $.ajax() is a callback – and receives three parameters. These are the XMLHttpRequest with the error, a type of error, and an error object, if one is thrown. For the most part, the first two are the only parts.

Now, the error attribute should be used for actual errors, not logical errors. For example, if you are making an AJAX call to log in the current user, and the user does not exist, this should return a success type message instead of some sort of error. Errors are things like 404′s for the AJAX call, or other HTTP issues. In fact, there are 4 types of errors that will be returned: Error – which is an HTTP error, parseerror – which is an xml/json parsing issue, timeout – which is a script that didn’t respond fast enough, and not modified.

I wrote a generic function to handle the errors. This could be name spaced I suppose or added to your standard library. In this case, it just alerts the error. (On some other sites, I generate a new modal box.)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function ajaxError(request, type, errorThrown)
{
	var message = "There was an error with the AJAX request.\n";
	switch (type) {
		case 'timeout':
			message += "The request timed out.";
			break;
		case 'notmodified':
			message += "The request was not modified but was not retrieved from the cache.";
			break;
		case 'parseerror':
			message += "XML/Json format is bad.";
			break;
		default:
			message += "HTTP Error (" + request.status + " " + request.statusText + ").";
	}
	message += "\n";
	alert(message);
}

In this function, an error message is generated based on the error type. The only error that gets extra information is the default type – which is ‘error’. It then retrieves the HTTP Status code and the Status Text.

Here is an example of this in use:
ajax.php

1
2
<?php
header('HTTP/1.1 503 Service Unavailable');

And, here is the test page. When the user clicks the xx link, it will generate a request to ajax.php. This will generate a 503 error and the error handler will take over.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
	<head>
	<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
	</head>
	<body>
		<a href="#" id="test">xx</a>
		<script type="text/javascript">
			$(function(){
				$("#test").click(function(){
					$.ajax({
						url: "ajax.php",
						success: function(){
							alert('retrieved');
						},
						error: ajaxError
					});
 
					return false;
				});
			});
		</script>
	</body>
</html>

Using Google Charts to make QR Codes

Tuesday, July 13th, 2010

QR Code for this page

QR Code for this page

Google Charts is my hero yet again. This time, I happened to notice that they have a chart in their API for QR Codes. Considering I was just searching google for a PHP class to do this, I was pretty ecstatic.

To implement, I made a quick line of jQuery to generate my QR Codes. Of course, I did this after the page loaded :) My goal was to generate a QR code for the page that the user is currently viewing. Pretty simple:

1
$("#qrImage").attr('src', 'http://chart.apis.google.com/chart?chs=150x150&cht=qr&chl=' + escape(window.location.href) + '&choe=UTF-8');

You can find all of the details and other parameters here: http://code.google.com/apis/chart/docs/gallery/qr_codes.html

Disable jQuery from loading in custom wordpress template

Tuesday, May 18th, 2010

On the rest of my site, I load jQuery from the google cdn. However, wordpress likes to load it from the local cache using wp_enqueue_script(). I didn’t want to delete the jQuery file it was loading because a) that would be wrong, b) it would still have to make a 404 call to the server, and c) the admin section uses it I’m sure.

Instead, I found there was a function called wp_deregister_script(). Using this, I removed the jquery from my header.php file – and continued to load it from the cdn. For reference, this is what I did:

1
<?php wp_deregister_script('jquery');wp_head(); ?>

IE6 warning on site

Thursday, April 22nd, 2010

So I got permission at the beginning of March to add an Internet Explorer 6 deprecation message to one of the sites I’m working on.

My goals are simple:

  • Do not pump the message out to search engines or anyone without IE6
  • Remind strongly but do not hinder the usage of the site

So, I felt the best way to do this was through a conditional comment. In the head of the document, the first thing I inserted is this:

1
2
3
<!--[if lte IE 6]>
<script type="text/javascript" src="/js/ie6warning.js"></script>
<![endif]-->

So, any browser that is Internet Explorer will understand this conditional comment. If it is Less Than or Equal to IE 6, it will load that javascript.

The javascript contains the following content:

1
2
3
4
$(function(){
	var ieDiv = $("<div id='ie6warning'><img src='/images/ie6logo.gif' alt='ie' /><div><h3>Did you know that your browser is out of date?</h3><p>To get the best possible experience using our website we recommend that you upgrade your browser to a newer version.<br />The current version is <a href='http://microsoft.com/ie'>Internet Explorer 8</a>.  The upgrade is free.  <em>(If you're using a PC at work you should contact your IT administrator.)</em> You may also try some other popular Internet browsers like <a href='http://getfirefox.com'>Firefox</a> or <a href='http://google.com/chrome'>Google Chrome</a>.</div></div>");
	$("#hd").prepend(ieDiv);
});

As you can tell, I’m using jQuery. However, the concept should translate to other javascript implementations as well. Basically, a message is created with a warning image. Then, the header element gets this box prepended to it.

Finally, we have a bit of css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/** ie 6 warning **/
#ie6warning {
	background-color: #FFFFDD;
	padding: 20px;
}
#ie6warning img {
	float: left;
	margin: 12px 0 12px 5px;
}
#ie6warning div {
	margin-left: 140px;
	padding-left: 27px;
	border-left: 1px solid #aaa;
} 
#ie6warning h3, #ie6warning p {
	margin: 0;
}

The finished product looks something like this:

Fixing c:\fakepath in filestyle jquery plugin

Friday, March 26th, 2010

The other day I ran across an issue with the FileStyle jquery plugin. Whenever a new file was chosen, windows and Internet Explorer would put c:\fakepath\ before the filename. Turns out its not FileStyle’s issue – but a security feature of Internet Explorer.

As a quick fix, however, I made the following changes to FileStyle:

BEFORE

1
2
3
4
5
6
//snip
            $(self).bind("change", function() {
                filename.val($(self).val());
            });
 
//snip

AFTER

1
2
3
4
            $(self).bind("change", function() {
            	var s = $(self).val().replace(/(c:\\)*fakepath/i, '');
                filename.val(s);
            });

Auto Failover for CDN based Javascript

Monday, November 30th, 2009

Using my javascript error reporter code helps me get a better understanding of what my clients are experiencing when visiting my website. One thing I did notice was the failures from time to time of Google’s CDN based Jquery.

To solve this issue, I decided to keep a local copy as well. For the most part, Google’s version is going to be faster and have a better cache method. However, I’d rather have an uncached version of it loaded into the user’s browser than nothing at all! So, in the very rare case that the user’s browser fails to load the Google javascript, I load a local copy of it.

First Step: Load JQuery From Google

The very first thing I do is to include jQuery from google’s code base using the following tag:

1
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

This will retrieve the latest version (1.3.2) from Google with the proper compression and cache response I like.

However, this sometimes was failing – well according to my error reporting script. What to do?

Test for a successful load of jQuery

Since the SCRIPT tag does not have an ‘onerror’ standard notifier like our image, the next best thing to do is test for the jQuery object right after the page loads. Since we’re using inline javascript, the first request to the external javascript will block while loading. When it completes, this small snippet will then execute.

I’ll jump ahead one more step though before code.

If no jQuery found, load it dynamically

If the jQuery object is not found, a new script element is created dynamically. The source is pointed to my local version of the script. Finally, it is appended to the head. Hopefully this will load the jquery. If it fails here, well then – the client has some issues!

This is the full inline javascript after the external javascript reference:

1
2
3
4
5
6
if (typeof jQuery == 'undefined') {
	var e = document.createElement('script');
	e.src = '/js/noncdn-jquery-1.3.2.js';
	e.type='text/javascript';
	document.getElementsByTagName("head")[0].appendChild(e);
}

In this case, the path http://mydomain.com/js/noncdn-jquery-1.3.2.js contains my local javascript.

The results?

Before this fix, I saw a failed jQuery load about once a day. I have not seen a single one yet. I have yet to see this error reported. If anyone finds a better way to do this, please let me know!

JfbConsole – chainable Firebug Console jQuery plugin

Thursday, November 12th, 2009

I find myself wanting to document various different attributes mid development on my jquery code. I have created the following function to help use FireBug’s console access code effectively in the jQuery fashion.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
 /**
  * JConsoleFB 0.1
  *
  * Jquery plugin for FireBug console integration.  Uses chainable method.  
  * See: http://getfirebug.com/console.html for options
  * @author Aaron Saray (http://aaronsaray.com)
  */
 $(document).ready(function () {
	 if (typeof window.console != 'undefined') {
		 jQuery.fn.log = function(msg) {
			 window.console.log("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.debug = function(msg) {
			 window.console.debug("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.info = function(msg) {
			 window.console.info("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.warn = function(msg) {
			 window.console.warn("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.error = function(msg) {
			 window.console.error("%s: %o", msg, this);
			 return this;
		 };
		 jQuery.fn.assert = function(expression) {
			 window.console.assert(expression, this);
			 return this;
		 };
		 jQuery.fn.dir = function() {
			 window.console.dir(this);
			 return this;
		 };
		 jQuery.fn.dirxml = function() {
			 window.console.dirxml(this);
			 return this;
		 };
		 jQuery.fn.trace = function() {
			 window.console.trace();
			 return this;
		 };
		 jQuery.fn.time = function(name) {
			 window.console.time(name);
			 return this;
		 };
		 jQuery.fn.timeEnd = function(name) {
			 window.console.timeEnd(name);
			 return this;
		 };
		 jQuery.fn.profile = function(title) {
			 window.console.profile(title);
			 return this;
		 };
		 jQuery.fn.profileEnd = function() {
			 window.console.profileEnd();
			 return this;
		 };
	 }
 });

Usage is pretty simple. For example, say I wanted to log something about the current element I’m going to clone. I may do this:

1
var newClone = $("#cloneable").log('Cloning this').clone();

This will display a reference to this object as well as the message ‘Cloning this’ in the Firebug console as a log type.

Form Submit: Internet Explorer behaving badly

Tuesday, April 14th, 2009

I just want to make a micro blog here. Just a tiny lil blog.

Internet Explorer Does Not Submit Form on Enter

Correct! Instead, I load my page with this jquery

1
2
3
4
5
6
    $('input').keydown(function(e){
        if (e.keyCode == 13) {
            $(this).parents('form').submit();
            return false;
        }
    });

Button Element Not Submitting in Internet Explorer

Correct! Mainly because I was lazy.

But in FireFox

  • twitter loader

Follow me on twitter: @aaronsaray

The views on this website are my own and do not reflect the opinions of my employer or clients.
Creative Commons License Home | Open Source | Book | Music | Art | Bio | Resume | Contact
My Baby