View Full Version : Degrading gracefully???

05-15-2010, 04:02 PM
1) Script Title: Dynamic Ajax Content

2) Script URL (on DD): http://www.dynamicdrive.com/dynamicindex17/ajaxcontent.htm

3) Describe problem: Id like it to degrade nicely!

Hi Guys... Thanks for the site - keep up the good work!

Ive just added the above scipt to my page, and it works wonderfully... But i was wondering if there was any way I could get it to work like normal links if there is no JS enabled on the end users browser? At the min it just doesnt work :-(

Thanks guys :-)


05-15-2010, 06:44 PM
That should be really easy. Try this and see if it works:

Right now the Javascript is acting as the href. Instead, use that as the onClick event, and keep the href as the actual URL you want:

<a href="javascript:ajaxpage('test.htm', 'contentarea');">test</a>

<a href="test.htm" onClick="return ajaxpage('test.htm', 'contentarea');">test</a>
"return" means that it will do this instead of doing the regular action (going to the page), but if that whole command is ignored, then it will go to the link like normal.

Here's the code once again a little cleaner:
<a href="test.htm" onClick="return ajaxpage(this.href, 'contentarea');">test</a>
this.href takes the URL from the link and uses it in ajaxpage so that you don't have to update both if you want to change it.

This should work very well. The only problem is that this relies on Javascript deciding whether it worked correctly. If it works, just do ajaxpage (no link); if not, just link (no ajaxpage).

But "works" is vague and if Javascript is enabled and believes it worked:
1) because most of it worked, but something wasn't enabled [like ajax]
2) because the ajax failed due to the server being down or user's connection not working
then the javascript may still believe it worked correctly.

But this will work in 95% of the cases, and certainly for the all (ajax) or none (just link) cases.

The only mess will be for older versions of Javascript or if something changed about the connection after the page was loaded-- like if the wifi user walked somewhere out of range.

05-16-2010, 09:01 AM
<a href="test.htm" onclick="ajaxpage(this.href, 'contentarea'); return false;">test</a>

Would be better. The ajaxpage function has no return value unless it fails, and then it's false. So returning it would fire the link when ajaxpage works and not fire the link when it fails, the opposite of what would be desired. If you wanted to put a fine point on it:

<a href="test.htm" onclick="return ajaxpage(this.href, 'contentarea') === false;">test</a>

Which would execute the link only if ajaxpage fails or javascript is unavailable.

05-16-2010, 09:14 AM
Ah, yes, that's better. I hadn't looked at the function's return values.