jQuery AJAX get() function cached in IE

From the 'how the heck were we supposed to know this?' department, a little tidbit I'd like to share, perhaps saving some poor, frustrated developer from the same type of mystifying madness:

jQuery "get()" operations are cached in IE unless you pass in a unique URL !

By cached, I mean, you can have a remote page with a query or other function, which responds to a unique set of values being passed in, and it will work fine in Firefox, but in IE, you'll get the same results from the remote page, even if the response is unique (like query results that have changed, for the same record), unless the values you are passing in via get() are also unique (i.e. you haven't looked up that particular record yet).

So, before you go banging your head on the floor and screaming out 'why oh why can't i find the problem, let alone the solution?!?' (not that i would ever do that), read this post, which i found via a quick Google search for 'jquery get IE cache' : http://www.sitecrafting.com/blog/ajax-ie-caching-issues/ 

I only had the presence of mind to run that search once i got my ajax results to display as an alert on the calling page, and deduced that the displayed content was based on the first values passed in, while all other updates and requests were ignored.

The fix, as that post suggests, is to create a unique url. In this case, i use javascript to append a random number to my function, - in this case, I just use javascript to create a random number right inline, then add that as a meaningles url variable to the page in the get() function:

                           // set up unique url
                            var randomNo = Math.floor(Math.random()*9999999);
                            var urlStr = 'journalLookup.cfm?r=' + randomNo;
                            // run get function using randomized URL
                            $.get(urlStr,{jdate:dateLookup}, function(data){  .... [ function here ]

If this saves you some aggravation, let me know in the comments ... maybe i'll feel better about the time i just wasted chasing this mystery 'feature' in IE!!

 

How to show changed input and select fields with jQuery

Here are a few quick easy jquery functions that will add a class of 'changed' to any input or select box if it is changed, and will remove that class if the value is reset to the default.



        // inputs
        $('form.myForm :input').change(function(){
        var defval = $(this)[0].defaultValue;
        if ($(this).val()!=defval){
            $(this).addClass('changed');
        } else {
             $(this).removeClass('changed');
        }
        }).keyup(function(){
             $(this).trigger('change');
        });

        // select boxes
        $('form.myForm select').change(function(){
        var defval = $(this).find('option[defaultSelected=true]').val();
        if ($(this).val()!=defval){
            $(this).addClass('changed');
        } else {
             $(this).removeClass('changed');
        }
        }).keyup(function(){
             $(this).trigger('change');
        });

Note in both cases we use keyup (onkeyup) to trigger the 'change' event. This allows the browser to show the changed class as soon as the user changes the value using a keyboard, rather than 'onblur'.

jQuery Cycle slideshow demo with next/back/paging links

This demo uses some of the advanced features of the jQuery Cycle plugin to create a mixed content slideshow (html/text/images) with a visual navigation bar, and next/back arrows

In this setup, the slideshow advances automatically, until somebody clicks one of the links, which stops the automatic action and allows the user to control the advancement of the slides. The Cycle plugin allows for pausing, resuming or stopping the slideshow with a simple click action.

See the demo (includes css/jquery code for easy reuse) http://www.gowestwebdesign.com/demos/jquery-cycle-gallery-next-back-paging/

Thanks to Mike Alsup for the versatile Cycle plugin: http://www.malsup.com/jquery/cycle/

Feel free to use the code for any purpose, and please drop me a comment or link to check out your work. As always, comments/suggestions/fixes are welcome.

jQuery form input defaultValue

When creating a form to accept user info, there are times when functions related to a form input's default value are required. For example, you have a field that says "search here", and when the user clicks in the field, the default value is removed so the user can begin typing. But, if the user leaves the field blank, you might want that default term to return. In regular javascript, we use something like this:


if(inputName.value == ''){
inputName.value = inputName.defaultValue
};

but jQuery doesn't have a built-in method for retrieving that default value. Thankfully, google found me a super easy workaround - this discussion thread holds the key:


if ($(this).val() == "") {
var defVal = $(this)[0].defaultValue;
$(this).val(defVal);
}

Note the [0] in the defaultValue. As explained in the thread linked above: "If you imagine $(this) as an array of DOM objects within jQuery, then $(this)[0] is a way to access the first (or in this case, only) DOM object. jQuery doesn't have a built in way to retrieve the default value of an input, so we have to nip back into the DOM momentarily in order to retrieve it. "

Marking current menu link with jQuery for CartWeaver categories

Working on a heavily-modified Cartweaver Coldfusion E-Commerce shopping cart site, I have created a database-driven navigation menu containing links to each category. When a user clicks a link, the products in that category are displayed, and the menu link for that category is highlighted via a special 'currentLink' css class.

Now of course I could use CF to add ' class="currentLink" ' to the current category's menu option, but I am not doing this particular menu that way. Besides, it is just as easy with jQuery!



<cfif cgi.script_name contains 'results.cfm' AND isDefined('url.category') and url.category gt 0>
<cfsavecontent variable="highlight">
<script type="text/javascript">
$(document).ready(function(){
$('.sideNav li a').removeClass('currentLink');
$('.sideNav li a[href=results.cfm?category=<cfoutput>#url.category#</cfoutput>]').addClass('currentLink');
//end jQuery
});
</script>
</cfsavecontent>
<cfhtmlhead text="#highlight#">
</cfif>

Simple enough - if we are on the 'results' page, and a category is defined in the url, remove the 'currentLink' class from all existing menu items, find the one where the 'href' attribute matches the current pagename and category, and add the class back to that link. Done.

The use of cfsavecontent and cfhtmlhead means I can put this right below the code that calls in my custom nav tag, for easy fine-tuning right where i need it (rather than in an external scripts file).

Quick , easy, and done in a flash with jQuery!

TwitterFeed and Tweet.js - feed your blog to Twitter, and your Twitter feed to any page

Two fun, free tools for blog/Twitter syndication combo:

1) www.twitterfeed.com : enter any Blog Rss feed url and twitterfeed will automatically post your blog entries to your twitter account

2) tweet.js : light, fast jQuery powered Twitter feed display - easy to configure options and show your Twitter posts on any page you choose

See both in action in the sidebar, here: www.gowestweb.com

Anything I post on this blog gets added to my 'gowestweb' twitter feed, which is shown on the GoWest site using tweet.js

Replace missing images sitewide with jQuery and ColdFusion

In my application.cfc, within the 'onRequestStart' function, I have a variable defined for the replacement image to use in my site.

Then, in an include that puts special goodies into the head of every generated html page sitewide, I have this bit of cf code



<!--- missing img src --->
<cfif fileExists(expandPath(request.missingImage))>
    <cfset imgErrorSrc = '#request.thisdir##request.missingImage#'>
<cfelse>
    <cfset imgErrorSrc = ''>
</cfif>

This checks to make sure the 'error' image actually exists - if not, we just use a blank '' value. (Note: request.thisDir is my own global variable that references the root of the site - you can replace that with any hardcoded or dynamic url)

Then, write a simple function to replace any images - this duplicates a similar usage of the tag's 'onerror' attribute ( which is fine for images in non-strict doctypes, but is not entirely valid ).



<!--- replace all missing images with replacement image, or with empty src --->
<script type="text/javascript">
$(document).ready(function(){
    $('body img').error(function(){
        $(this).attr('src', '<cfoutput>#imgErrorSrc#</cfoutput>').attr('alt','');
    });
});
</script>

That's it. Also notice I am clearing the 'alt' attribute as a final precaution. Using this method, any missing image anywhere within the html will simply be 'blanked out'.

I could use jQuery's .remove() function, to remove a missing image completely from the DOM, but there are times when I want the space or layout to be preserved, and really, I don't want errant images in my pages at all, so this gives me a way to debug if I find my self (inevitably) scratching my head when a missing image simply 'vanishes' from the page 4 or 5 sites from now.

As a final note, the CF part of this, setting the value for the 'src' attribute, can be enhanced to include different images for different pages, or under different conditions. Likewise, the jQuery function could be expanded to target images in one location with a specific action, and in another with a separate function by using different css selectors.

Just another example of how Jquery + CF = bliss :-)

Remove missing images (and parent elements) using jQuery

My client has an auto dealership site where inventory images are pulled remotely, i.e. 'hotlinked', from the inventory service's website. The client asked me to create a slideshow of inventory images on the home page - no problem using jQuery cycle() plugin - but there's one hangup: some of the images don't exist!  Easy enough to remove the images ( <img onerror="this.style.display = 'none'"> ) , but these images are dynamically linked, and contained in an unordered list. So, even if I remove the errant images with an inline attribute, I still have this empty 'a' and 'li' hanging around.

Using a single line of jQuery code, I whipped up this super-quick solution:

<script type="text/javascript">
$(document).ready(function(){

// find all missing images
$('#slideshowWrap img').error(function(){

// hide the image, then remove the parent element from the DOM
$(this).hide().parents('a').parents('li').remove();

// uncomment line below to see the script at work
//alert('hidden: ' + $(this).attr('src'));

});

// end jquery
});
</script>


The parents('a') could become parents('p') or whatever is needed to get rid of the containing element.

Maybe the 'hide()' combined with 'remove()' is redundant.... but I like it.

That 'alert' line, if uncommented, will alert you to the src of each missing image for testing.


jQuery validate() plugin, IE6, simple solution

I have been using the jQuery validate plugin for just about every form I've created in the past year or more. Easy, robust, beautiful stuff by world-class jQuery coder Jörn Zaefferer ( plugin page ) ... if you haven't checked it out yet, please do!

Anyway, tonight I had (yet another) strange thing happen in IE6 - basically, nothing was happening. The form i was working on was able to submit in IE6 as if javascript was disabled - no errors, no message, nothing. As usual, everything was fine in Firefox (firebug) and IE7, and I was stumped as only IE6 can stump me... then, thanks to Google, I found this thread: http://groups.google.com/group/jquery-en/browse_thread/thread/843bc94ffef99250

Apparently there is something in the packed version of the validation file (jquery.validate.pack.js) that IE6 does not like. The solution? Don't use the packed version! Takes up a little more bandwidth but at least it works in all browsers.

Now - how much longer do we have to keep caring about IE6? (In this case, the offending browser is on the client's computer, so I have to play nice as much as possible...)

CF Gallery Creator & jQuery Slider Gallery !New and Improved!

Still a work in progress, I have fixed a few small things and added better setup notes for the CF Gallery Creator and jQuery Slider Gallery (click for explanation in previous post)

The new code is available as a zip file, attached ** see below **

This package contains

1) a custom ColdFusion image gallery generator, which will create thumbnails and large images of any size you specify from a folder containing your original images, and outputs them to the page in a nice unordered list html markup.

Includes options for multiple subfolders, each one a separate 'gallery' with thumbnail or dropdown navigation.

 

2) a simply but effective 'slider gallery' built on css and jQuery. Example here:

http://www.gowestweb.com/cfdev/_tags/gallery/slidergallery.cfm?gallery=some-gallery-name

( Without the jQuery and css, the raw markup from the CF tag alone looks like this
http://www.gowestweb.com/cfdev/_tags/gallery/gallerypage.cfm?gallery=some-gallery-name

 

As usual this was built to meet a specific need for a client project and has been tweaked and adjusted along the way.

Please DO try it out, and let me know if/when you use it.
Comments, enhancements and suggestions welcome!

Some alternatives to Adobe NNTP Newsgroups

As many dedicated web developers mourn the passing of the NNTP interface for Adobe's support forums ( formerly nntp://forums.adobe.com ), I'd like to extend a hearty welcome, inviting all web developers, friends and interested cohorts to join myself and a number of other seasoned web professionals in some popular NNTP-friendly alternative hangouts.

http://www.miuaiga.com/page.cfm/Web-Developer-Newsgroups

In addition to general web developer newsgroups, there are some specialized groups for ColdFusion, javascript (ok, mostly jQuery), all three flavors of CartWeaver (E-commerce) and more.

Every one of the newsgroups listed on the page above is happy to welcome new and interesting contributors, the more the merrier. You may even discover some old friends among the archived threads. 

NOTE: If you are not currently using NNTP to interact with other web-folks online, you've been missing out! I recommend Mozilla Thunderbird, and an account at each one of the places listed. See you there!

---

In regards to the big switch, the Adobe Dreamweaver support forum says this:

ANNOUNCEMENT: Forums will be unavailable for planned system maintenance
starting at 3pm PST on April 3, 2009. New forums will be online on
Monday April 6, 2009.

( currently April 3, 1:35 Pacific time ... T-minus 90 minutes )

More Entries

blogcfc 5.9.1.002 by raymond camden
contact michael evangelista