Advertisement

Learn Photoshop, Flash, Adobe AIR, ExtJS, jQuery, Ajax, Dojo, HTML, CSS, JavaScript, XML, Accessibility, Database, DWR, Gears, GWT, Java, JSON, MooTools, Office, Perl, PHP, Programming, Prototype, Scriptaculous and more, Want to explore your choice of videos from all over world at once place! then what are you waiting for, just click, explore and learn.
And if you are a sports person, enjoy videos of Sports - below are the latest sports videos which you have ever seen before.

How to resolve browser compatibility issues while working with JavaScript, AJAX and XML

Categories: AJAX, Browsers, Featured, HTML, JavaScript, Programming, xml
Tags: , , , ,
Written By: admin

Advertisement



After going through this article, you will get an idea on resolving browser compatibility issues while working on JavaScript, AJAX and XML. I think, most of the developers might have faced browser compatibility issues while working with AJAX and XML, by assuming XML as a back-end database to retrieve respective data depending the events or requests sent by the user.  When we run an application which you develop using AJAX and XML it behaves differently in different browsers like mostly in IE (Internet Explorer) and Mozilla Firefox.

Brief description about JavaScript, AJAX and XML:

AJAX:

What is AJAX?
AJAX (Asynchronous JavaScript and XML), it is combination of interrelated web development techniques which is used to create interactive web applications or RIA’s (Rich Internet Applications)

What the World says about AJAX

Who’s Using AJAX (Many More)

JavaScript:

What is JavaScript?

JavaScript is a Scripting Language used for client-side web development, this is also well known as client-side scripting language. Using JavaScript, we can develop interactive web sites and it is well influenced by many languages and it is very easy to learn and develop interactive web sites and web applications.

XML:

What is XML?
XML is a Extensible Markup Language for documents containing structured information. And was designed to transport and store data.

Coming back to this article, How to resolve browser compatibility issues while working with JavaScript, AJAX and XML

While I was working on a project, I have faced many browser compatibility issues like how to ignore white space while writing code in JavaScript. I observed that, IE (Internet Explorer) browser is ignoring white space but Mozilla (Firefox) and other Netscape Browsers are not ignoring white spaces.

Where I have faced the issue? When I was trying to retrieve the length of childnodes in respective parent node. While I was retrieving the same Mozilla Firefox Browser behaves in a different way that IE browser. Actually, I have only ‘2 child nodes’ in a parent node. IE shows the length (nParentNode[0].childNodes.length) as 2 but when I execute the same code in mozilla the respective result was different – this was not my expected result, it should be 2 in mozilla as well.

After doing some research on this, I observed that IE is ignoring whitespaces but coming to Mozilla and other browser’s were not ignoring whitespaces, to over come this issue we have to use one extra line of code in JavaScript:

1
2
3
4
5
for (var j=0;j<nParentNode[0].childNodes.length;j++)
	{
		if (nParentNode[0].childNodes[j].nodeType != 1) continue;
		...continue with the code...
	}

If you look at the above code, the condition in ‘if statement’ does our job. My plan is to ignore whitespaces, this is possible using ‘nodeType‘ the above if condition checks for ELEMENT_NODE, if it is other than ELEMENT_NODE that is ATTRIBUTE_NODE (or) TEXT_NODE (or) ENTITY_NODE etc., it continues the loop. Below table depicts NodeTypes and its Named Constants:

NodeTypes, related Named Constants

NodeType Named Constant
1 ELEMENT_NODE
2 ATTRIBUTE_NODE
3 TEXT_NODE
4 CDATA_SECTION_NODE
5 ENTITY_REFERENCE_NODE
6 ENTITY_NODE
7 PROCESSING_INSTRUCTION_NODE
8 COMMENT_NODE
9 DOCUMENT_NODE
10 DOCUMENT_TYPE_NODE
11 DOCUMENT_FRAGMENT_NODE
12 NOTATION_NODE

Look at the XML file, which I am using as an example:

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<data>
      <Orgs>
        <Organization label="Organization">
          <OrgName txt="Google"/>
          <OrgSize txt="10,000 - 30,000 Employees"/>
        </Organization>
        <Technology label="Technology">
          <TechnologyName txt="Wireless"/>
        </Technology>
      </Orgs>
</data>

In the above XML, <Orgs> is parent tag to <Organization> and <Technology> that is <Organization> and <Technology> are child nodes. My aim here is to know how many child nodes are there in <Orgs> node, and to get data from those child tags. If you look at the JavaScript code:

1
2
3
4
5
for (var j=0;j<nParentNode[0].childNodes.length;j++)
	{
		if (nParentNode[0].childNodes[j].nodeType != 1) continue;
		...continue with the code...
	}

nParentNode is pointing to <Orgs> and nParentNode[0] indicates the very first node of parent, childNodes is a property which returns a NodeList containing the child nodes of the respective selected node. length depicts the number of child nodes.

1
nParentNode[0].childNodes.length

If you execute the above line in IE browser it gives the result as “2″ but if you execute the same in Mozilla Firefox or other Netscape Browsers it gives the result as “4″ because of whitespace. So, in order to over come this types of issues we can make use of nodeType and our problem can be solved, that is a simple ‘if condition’ will solve our problem.

Example:

XML

XML Filename: data.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<data>
      <Orgs>
        <Organization label="Organization">
          <OrgName txt="Google"/>
          <OrgSize txt="10,000 - 30,000 Employees"/>
        </Organization>
        <Technology label="Technology">
          <TechnologyName txt="Wireless"/>
        </Technology>
      </Orgs>
</data>

JavaScript

JavaScript Filename (AJAX Code): data.js

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
64
65
66
67
68
69
70
//Author: DeveloperSnippets.com
//Global Variables
var httpRequest = false; //Initially setting the Http Request to false 
var	nParentNode = 0; // No.of Parent nodes
var aParentChildNodes=new Array(); // Parent Child Nodes
var parentTagLabels=new Array(); // Parent Child Nodes Labels
var childTxtLabels=new Array(); // Parent Child Nodes Labels
var statusText="document.getElementById('statustxt')"; // Status of the Records
 
// Configuring XML Function
function xmlConfiguration(xmlFile)
{
      httpRequest = false;
      if (window.XMLHttpRequest) { // For Mozilla, Safari,... Browser's
         httpRequest = new XMLHttpRequest();
         if (httpRequest.overrideMimeType) {
            httpRequest.overrideMimeType('text/xml');
         }
      } else if (window.ActiveXObject) { // For IE Browser
         try {
            httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!httpRequest) {
         alert('Cannot Create XMLHTTP Instance');
         return false;
      }
      httpRequest.onreadystatechange = orgInformation; //onready state call a function named orgInformation
      httpRequest.open('GET', xmlFile, true);
      httpRequest.send(null);
}
 
//If the request is success then orgInformation() function is called
function orgInformation() 
{
  if(httpRequest.readyState == 0) { eval(statusText).innerHTML = "Sending Request..."; }
  if(httpRequest.readyState == 1) { eval(statusText).innerHTML = "Loading Response..."; }
  if(httpRequest.readyState == 2) { eval(statusText).innerHTML = "Response Loaded..."; }
  if(httpRequest.readyState == 3) { eval(statusText).innerHTML = "Response Ready..."; }
  if(httpRequest.readyState == 4) 
	{
	 if (httpRequest.status == 200) 
		{
			nParentNode = httpRequest.responseXML.getElementsByTagName("mastersearch");
 
			var i=0;
			for (var j=0;j<nParentNode[0].childNodes.length;j++)
			{
				if (nParentNode[0].childNodes[j].nodeType != 1) continue;
				aParentChildNodes[i] = nParentNode[0].childNodes[j].nodeName; //Master Child Node Names
 
				aMasterChildSibNodes[i]=nParentNode[0].childNodes[j].childNodes[j].nodeName; // Master Child Sibling Node Names
				var mainTagNodes=eval(nParentNode)[0].getElementsByTagName(aParentChildNodes[i]); //Here <Organization>,<Technology>
				parentTagLabels[i]=mainTagNodes[0].getAttribute("label");
				var childTagNode=mainTagNodes[0].getElementsByTagName(aMasterChildSibNodes[i]); //<OrgName>
				childTxtLabels[i]=childTagNode[0].getAttribute("txt");
				i++;
			}
			//alert(aParentChildNodes+" "+aMasterChildSibNodes+" "+parentTagLabels);
			document.getElementById('result').innerHTML=aParentChildNodes+" "+aMasterChildSibNodes+" "+parentTagLabels;
		}else
		{
			alert('There was a problem with the XML request.');
		}
	}
}

HTML

HTML Filename: data.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script src="data.js"></script>
</head>
<body>
<div id="statustxt"></div>
 
<div id="result"></div>
<script language="javascript">
xmlConfiguration('data.xml'); 
</script>
</body>
</html>

Hope this might help you in solving some of the issues which you are facing. If you have any comments, please do let me know.

Articles which you would like to read:

Advertisement



2 Responses to “How to resolve browser compatibility issues while working with JavaScript, AJAX and XML”

  1. Binny V A Says:

    You don’t have to use XML for Ajax – there are many other formats as well. Currently, most developers prefer and recommend JSON.

  2. How to Get Six Pack Fast Says:

    If you want to see a reader’s feedback :) , I rate this article for 4/5. Detailed info, but I just have to go to that damn google to find the missed pieces. Thanks, anyway!

Leave a Reply





Featured & Popular Articles

Online Sponsor