What should be the ideal fallback method? - javascript

I am using Ajax to call for a special file if JavaScript is enabled and if it is disabled then it loads the regular file.
My Code is like this:
window.onload = function() {
document
.getElementById("wrapper")
.innerHTML = "<img src='cdn/img/demo/loading.gif'>";
var x = null;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var x = new XMLHttpRequest();
} else if (window.ActiveXObject) {
// code for IE6, IE5
var x = new ActiveXObject('MSXML2.XMLHTTP.3.0');
} else {
// #TODO - Fallback
// My Question : What should be an ideal Fallback method here?
}
x.open("GET", "js_enabled.php", true);
x.send("");
x.onreadystatechange = function() {
if (x.readyState == 4) {
if (x.status == 200)
document.getElementById("wrapper").innerHTML = x.responseText;
else
document.getElementById("wrapper").innerHTML = "Error loading document";
}
}
}
What should be an ideal Fallback method in the first block?
UPDATE:
The fallback is for the browsers. As you see that those commands are for IE and normal browsers. I want to know if god forbid some browser does not understand ant of those 2 commands then what?

AJAX is extremely likely to be available if JS is available, so it's not something you'll have to deal with often, but if you're looking for a fallback when AJAX isn't available (which I'm guessing you are from your code example), then the only real way of doing that is making sure that your page works fine without it.
Links should point to appropriate pages (or just to reloading the current page) and then be overwritten with the JS to use AJAX (but only if AJAX is available). That way you'll have a functioning site even if JS isn't available, let alone if AJAX isn't.
To give you some idea of how small the problem is when it comes to lack of AJAX support, according to this site browsers that include AJAX support include the following:
Internet Explorer 5.0 and up
Opera 7.6 and up
Netscape 7.1 and up
Firefox 1.0 and up
Safari 1.2
As you can see, that's some pretty old stuff.

you are confused if javascript is disabled then there will be no fallback method. Assuming that you mean anabling/disabling of javascript.
Then what you do is fill up the area with default text and hide it using js. so if JS isnt enabled the default text will be shown to the user.
and if js is enabled the default text will be hidden almost as soon as it is rendered and then your ajax thing will take over

Related

Porting Issue - Internet Explorer to Everything Else

I have some code which was developed on a Windows 7 computer and runs any Windows 7 compeer without any hiccups. I tried running it on my Mac and the program just stays on the loading page.
The program displays the bing maps view and loads a few things in order to get the location of a particular satellite. Now all the maths and stuff works but I think the problem lies here:
function getOrbitalElements()
{
TLE_Line1="";
TLE_Line2="";
pgTXT = "";
xmlhttp = null;
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
if (xmlhttp!=null)
{
xmlhttp.onreadystatechange = stateChange;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
}
So is there any way that this can be changed to run on any browser? Thanks
P.S. If you need to see the entire code I'll add it
There are no ActiveX objects on Mac. The following line won't work:
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
You could use XMLHttpRequest:
var xmlhttp = null;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xmlhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp != null) {
...
}
But if you are seeking best cross browser support I would recommend you using a javascript framework such as jQuery to perform your AJAX requests.
Replace
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
with
xmlhttp = window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
EDIT
As others have said, you might find benefit in using something like jQuery (which is very good) but you may not need to take the effort to adjust your existing code just yet. If you have written good (standards) javascript, you will find the browser cross-compatibility issues should be minimal.
In the future, be sure to test in other browsers early and often to avoid this kind of problem.
The best way to port a particular web app from a Browser specific version to a browser agnostic one is to use a javascript framework like jQuery. It's designed to smooth out the rough edges that come up between different browsers into a friendly + unified API. For example the above code could be done across multiple browsers with a jQuery ajax request
$.ajax({
url: url,
success: function () {
// Called when the query completes
statechange();
}});

Why does this JavaScript work on Safari, but not Firefox?

I have HTML file. I tried the code on Safari and it was working fine. But when I tried this on Firefox, it’s not working.Can anyone suggest how to make it working on firefox?
On click on undo button I want to retrieve contents from the jsp file. Thats working when I used this code on safari on my mac.. but when I open the same file using firefox its not working. I am not sure is it due to browser settings or due to some other reason. I checked browser setting of firefox 3.6.12 installed on mac also it is enabled for javascript and java...
When I checked on HTTPfox it showed in Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED) in the contents
Can anyone suggest whats going wrong???
XMLHttpRequests only work when the request is on the same domain as the JavaScript making the request. So, your call to xmlHttp.open() would only work if that HTML file was hosted on csce.unl.edu.
Can the ubuntu box access the url http://csce.unl.edu:8080 ? It may be network/proxy/firewall settings on the virtual machine or in Firefox settings.
I'd try running firefox on the Mac and see where that takes me. If that doesn't work Then the problem is the browser, if it does, it's the way you are loading the site
Use JQuery. It has an AJAX library which does these browser compatibility checks for you.
Also, Firebug may come in handy, to see whether the request is being sent and see what the response is.
I opened firebug > console and pasted
var xmlHttp, handleRequestStateChange;
handleRequestStateChange = function() {if (xmlHttp.readyState==4 && xmlHttp.status==200) { var substring=xmlHttp.responseText; alert(substring); } }
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce.unl.edu:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange; xmlHttp.send(null);
And i saw everything working. What the error exactly? Can you open firebug and look at javascript errors.
Edit try this:
var req = new XMLHttpRequest();
req.open('GET', '/');
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
alert(req.responseText);
else
alert("Error loading page\n");
}
};
req.send(null);

AJAX document.getElementById().innerHTML problem with IE?

Before someone said that I did not read I may say that I read almost everything linked with my question. But I couldn't find my answer.
So, I have a simple AJAX script that loads my external file inside predefined div. This is the code of those script:
function loadTwitter()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your Browser Don't Support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById("column_twitter").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("GET","../includes/home/twitter.php",true);
xmlHttp.send(null);
}
It works just fine in everyone browser that I test (FF, Opera, Chrome, Safari), but inside IE7 don't want to inject my external php file into predefined div. It always stays the default text that I wright inside div...
And I think that the problem is in this row:
document.getElementById("column_twitter").innerHTML=xmlHttp.responseText;
So, any suggestions how to fix this for IE (7 and above)?
I think you'd be better off using a javascript framework such as jQuery that allows you to concentrate on getting your features implemented rather than browser compatibility and low level network interaction. Using jQuery you could simply do:
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js">
</script>
<script type="text/javascript">
$.get( '../includes/home/twitter.php', function(data) {
$('#column_twitter').html( data );
});
</script>
I know that this is an old question, but I ran into a similar thing today and I wanted to post it out for others in case you experience this issue. This is likely being caused by your "column_twitter" tag being embedded in multiple DIV statements or in a table. IE7 doesn't like this for some reason.
Good Luck!

What is the correct way to detect Opera using jQuery?

Amazon.com recently updated their javascript, and it's causing problems with some Opera browsers.
Their browser detection code looks like so, but it's faulty:
function sitbReaderIsCompatibleBrowser() {
if (typeof(jQuery) == 'undefined') {
return false;
} else {
var version = jQuery.browser.version || "0";
var splitVersion = version.split('.');
return (
(jQuery.browser.msie && splitVersion[0] >= 6) // IE 6 and higher
|| (jQuery.browser.mozilla && (
(splitVersion[0] == 1 && splitVersion[1] >= 8) // Firefox 2 and higher
|| (splitVersion[0] >= 2)
))
|| (jQuery.browser.safari && splitVersion[0] >= 500) // Safari 5 and higher
|| (jQuery.browser.opera && splitVersion[0] >= 9) // Opera 5 and higher
);
}
}
Nothing obviously wrong jumps out at me with this code, but I've never used jQuery before so I don't know.
Even though this code looks like it's attempting to let Opera users through, when I visit the page with Opera 9.64 I get an "unsupported browser" message. If I change Opera's settings to report itself as Firefox, the page works perfectly! With that in mind, I'm pretty sure it's a problem with the script and not the browser.
Any jQuery experts have a suggestion?
You can replicate the behavior by visiting any book on Amazon and clicking the "look inside this book" link.
Prior to jQuery 1.3, you could use jQuery.browser:
if( $.browser.opera ){
alert( "You're using Opera version "+$.browser.version+"!" );
}
From version 1.3, you should use jQuery.support instead.
Main reason for this is that should should avoid checking for browsers, as features may change from version to version, making your code obsolete in no time.
You should always try to use feature detection instead. This will allow you to see if current browser supports the feature you're trying to use, regardless the browser brand, version, etc.
There is a special window.opera object which is present in all Opera 5+ browsers. So something as simple as:
if (window.opera && window.opera.buildNumber) {
// we are in Opera
}
would be enough.
I check for Opera like this:
if (/Opera/.test (navigator.userAgent)) // do something
Why would you want jQuery?
It is much better to detect javascript capabilities rather than browser userAgent.
ie DOM, XmlHttpRequest, eventing model (event.target vs event.srcElement), ActiveX, Java etc
By focusing on the API functions that you will require, rather than a target browser you will create a more robust set of scripts, and inevitably less special casing.
This link here at opera will probably tell you more
A very simple way from Opera themselves:
if (window.opera) {
//this browser is Opera
}
Source: http://my.opera.com/community/openweb/idopera/
The main reason why Amazon fails on Opera is because the send different code from the server side already... If you visit the same page with Firefox and then save that page and reopen it in Opera it works fine...
But they promised to fix that sometime in January...
I think this way is the best
if ( window.opera.version() == 12) {
}
This example check if opera version is 12. Very useful when I have problems with font-face in Opera.
I don't know for sure ( i never really check for opera anyway) but if the built-in jQuery functionality doesn't detect opera, may be a bug with the jQuery which needs to be fixed. I would suspect if that's the case, it should get resolved fairly quickly.
In current HTML5 times, you can also check for browser features instead often.
if (!window.FormData) { alert("xmlhttprequest L2 FormData interface not available"); }

Is there a way to have browsers ignore or override xml-stylesheet processing instructions?

I'm trying to write a bookmarklet to help some QA testers submit useful debugging information when they come across issues. Currently I can set window.location to a URL that provides this debugging information, but this resource is an XML document with an xml-stylesheet processing directive.
It would actually be more convenient if the testers were able to see either the raw XML data as plain text, or the default XML rendering for IE and Firefox.
Does anyone know a way to disable or override xml-stylesheet directives provided inside an XML document, using Internet Explorer or Firefox?
Edit: I've opened a bounty on this question. Requirements:
Client-side code only, no user intervention allowed
Solutions for both IE and Firefox needed (they can be different solutions)
Disabling stylesheet processing and rendering it as text is acceptable
Overriding stylesheet processing with a custom XSL is acceptable
Rendering the XML with the browser default XML stylesheet is acceptable
EDIT: too bad, though all seemed fine in the preview, the clickable examples seem to mess up things... Maybe the layout is fine in the history.
I've heard, but cannot validate for IE, that both IE and Firefox support the "view-source:" pseudo-protocol. Firefox on Mac indeed understands it, but Safari does not.
The following bookmarklet will not trigger the XSLT transformation specified in the XML. And though Firefox will render this using some colours, it does not execute the default transformation it would normally use for XML without any XSLT (so, the result of view-source does NOT yield a collapsable document tree that Firefox would normally show):
javascript:(function(){
var u = 'http://www.w3schools.com/xsl/cdcatalog_with_ex1.xml';
var w = window.open();
w.document.location.href = 'view-source:' + u;
})()
When fetching the document using Ajax then one is not limited to the alert oneporter used, but can display it in a new window as well. Again: this will not invoke the XSLT transformation that is specified:
javascript:(function(){
var u = 'http://www.w3schools.com/xsl/cdcatalog_with_ex1.xml';
var w = window.open(); /* open right away for popup blockers */
var x = new XMLHttpRequest();
x.open('GET', u, true);
x.onreadystatechange = function(){
if(x.readyState == 4){
w.document.open('text/html');
/* hack to encode HTML entities */
var d = document.createElement('div');
var t = document.createTextNode(x.responseText);
d.appendChild(t);
w.document.write('<html><body><pre>'
+ d.innerHTML + '</pre></body></html>');
w.document.close();
w.focus();
}
};
x.send(null);
})()
Can't you just do "View Source" in both browsers?
You can avoid a processing instruction by using an intermediary step to pre-process the XML before the content is output in the browser.
Client-side suggestion
Retrieve the relevant XML document via an AJAX request
Parse the XML into a DOM (note: a DOM not the DOM)
Traverse the DOM and render in the browser the required data
Server-side suggestion
Instead of directly requesting the pertinent XML document, make a request instead to a proxy script that removed from the XML content all processing instructions, or indeed all that you don't want.
Instead of:
window.location = 'http://example.com/document.xml';
use:
window.location = 'http://example.com/proxy/';
The script at http://example.com/proxy/ would:
Load document.xml
Use whatever is necessary to remove the processing instruction from the XML content
Output the XML content
As long as you wouldn't have to deal with cross domain permissions, a simple ajax request / alert box with the XML source would do the trick. You'll have to add a little bit to the xmlHttp declaration to make it compatible with IE.
<html>
<body>
<script language="JavaScript">
function ajaxFunction()
{
var xmlHttp=new XMLHttpRequest();;
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("GET","YOURFILE.xml",true);
xmlHttp.send(null);
}
</script>
Errors
</body>
</html>
As far as I know, there is no way of doing what you are trying to do. The issue is, javascript cannot read the dom of the xml from a client side xml/xsl transform. As far as the javascript is concerned, it is executing on a normal html dom.
However, there may be some hope depending on the type of webapp. You could use ajax to get the xml of the current url. As long as there is no post data, or any other randomness, this method should work fine.

Categories

Resources