AJAX not working in Chrome and Firefox

The following piece of AJAX code does not work in Chrome and Firefox. Any ideas?
<html>
<head>  
<script type="text/javascript>
var xmlDoc;
        function loadFunction() {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

            xmlDoc.async = false;
            xmlDoc.onreadystatechange = yourfunctionname;

            xmlDoc.load("yourxmlfilefilename.xml");
        }

        function yourfunctionname() {
            if (xmlDoc.readyState == 4) {

                var item = xmlDoc.getElementsByTagName("item");
                alert("The item is : " + item);

                //use the 'item' to populate the HTML tags.  
                 
            }
        }
</script>
</head>
<body onload="loadFunction();">

</html>
prainAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

hieloCommented:
>>new ActiveXObject(...)
The above only works for IE.  Try the following:

...
 function loadFunction() {
            try{
                 xmlDoc = new XMLHttpRequest();
            }
            catch(e)
            {
                 xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            }
            xmlDoc.async = false;
            xmlDoc.onreadystatechange = yourfunctionname;

            xmlDoc.load("yourxmlfilefilename.xml");
        }
...

Open in new window

0
prainAuthor Commented:
Your hint led me to do this way..and then I added an alert() box in the  
yourfunctionname() {} . Now on IE this works good. But in Chrome and Firefox even the alert() is not popping up meaning the callback function yourfunctionname() never gets called.

Any ideas why?


function loadContacts()
         {
            if (navigator.userAgent.search("MSIE") >= 0){
                 xmlDoc = new ActiveXObject("Microsoft.XMLDOM");              
         }
            else if (navigator.userAgent.search("Chrome") >= 0 ||
                     navigator.userAgent.search("Firefox") >= 0)
            {
               
                 xmlDoc = new XMLHttpRequest();
             }

             xmlDoc.async = false;
             xmlDoc.onreadystatechange = yourfunctionname;
           
             xmlDoc.load("yourxmlfilefilename.xml");
         }

function yourfunctionname() {
 alert("Passing Other");
            if (xmlDoc.readyState == 4) {

                var item = xmlDoc.getElementsByTagName("item");
                alert("The item is : " + item);

                //use the 'item' to populate the HTML tags.  
                 
            }
0
MiramacesCommented:
i would recommend to use a framework like jQuery, so you don't have to struggle with different browsers.

http://api.jquery.com/jQuery.ajax/

but the answer from hielo is of course also correct ;)
0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

hieloCommented:
>>xmlDoc.load
load() is a method implemented by "Microsoft.XMLDOM"(http://msdn.microsoft.com/en-us/library/ms757828(v=vs.85).aspx), which in turn works only in IE.  XHMHttpRequest() does not have a load method:

IE's XMLHTTPRequest
http://msdn.microsoft.com/en-us/library/ie/ms535874(v=vs.85).aspx

Firefox XMLHTTPRequest
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

In your case instead of "load()", you have to send a "GET" request to the server instead (your xml file and the page that contains the script below need to be running on the same web server):

function loadContacts()
{
	if (window.XMLHttpRequest)//non-IE
        {
		xmlDoc = new XMLHttpRequest();
	}
	else if(window.ActiveXObject)//IE
	{
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
	}

	if( xmlDoc )
	{
             xmlDoc.onreadystatechange = yourfunctionname;
             xmlDoc.open("GET","yourxmlfilefilename.xml",true);
             xmlDoc.send('');
	}
}

function yourfunctionname()
{
	alert("Passing Other");
	if (xmlDoc.readyState == 4)
	{
		if( xmlDoc.status!=200 )
		{
			alert('Expected Status 200.  Received ' + xmlDoc.status + ' status instead!');
		}
		else
		{
			alert("Data: " + xmlDoc.responseText);
			
                var item = xmlDoc.getElementsByTagName("item");
                alert("The item is : " + item);

                //use the 'item' to populate the HTML tags.   
		}                 
	}
}

Open in new window


On another note, this is considered bad practice:
>> if (navigator.userAgent.search("MSIE") >= 0)

Instead of trying to determine which browser the user is using, you should be trying to determine if the browser in question supports the "thing/utility" you need.

XMLHttpRequest() is supported by the latest versions of IE (I believe starting with IE 7). By using the try{}catch(){} (or the "equivalent" if-else  clause above) all the major browser and the recent IE versions will use the XMLHttpRequest().  Only the older versions of IE will use "Microsoft.XMLDOM".
0
prainAuthor Commented:
It appears the getElementbyTagName() is breaking in Chrome and/or Firefox.
I am posting a skeleton of the application where some rates are displayed in a simple list box. This works well in IE.

in the code,  when
    if ( xmlDoc.readyState == 4)
    {
       alert("Passed 1");    //This line is executed in Chrome and Firefox
   
       //Nothing is executed below the above alert()

    }

Please see the code.


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

     <script type="text/javascript">
         var xmlDoc;
         function loadRates()
         {
             if (navigator.userAgent.search("MSIE") >= 0)
             {
                xmlDoc = new ActiveXObject("Microsoft.XMLDOM");

                xmlDoc.async = false;
                xmlDoc.onreadystatechange = readRates;
               
                xmlDoc.load("PartialRates.xml");
             }
             else if (navigator.userAgent.search("Chrome") >= 0 ||
                     navigator.userAgent.search("Firefox") >= 0)
             {
                xmlDoc = new XMLHttpRequest();

                xmlDoc.onreadystatechange = readRates;
                xmlDoc.open("GET", "PartialRates.xml", true);
                xmlDoc.send();
             }
         }

         function readRates()
         {
             var phoneRateNames=["rate1","rate2","rate3","rate4","rate5"];
             var maxStringWidth = 52;
             
             if (xmlDoc.readyState == 4)
             {
                 alert("Passed 1");
                var rateAttributes = xmlDoc.getElementsByTagName("partialRates")[0].attributes;
                var itemsLength = rateAttributes.length;

                alert("Length : " + itemsLength);

                var numberOfEvents = item.length;
                var rate1, rate2, rate3, rate4;
                 
                for (var nextAttribute = 0; nextAttribute < itemsLength; nextAttribute++)
                {
                  var readRate = rateAttributes.getNamedItem(phoneRateNames[nextAttribute]).value;
                  var country, rate;
                  for (nextChar = 0; nextChar < readRate.length; nextChar++)
                  {
                    if (isNaN(readRate.charAt(nextChar)))
                    {
                      //Do not do anything
                    }
                    else
                    {
                      country = new String("" + readRate.substring(0, nextChar));
                      rate = new String("" + readRate.substring(nextChar + 1));
                      break;
                    }
                  }
                  var result = new String(country);
                  for (var fillBlnk = 0; fillBlnk < (maxStringWidth - country.length - rate.length) ; fillBlnk++)
                      result = result + " ";
                  if (nextAttribute == 1) result = result + "  ";
                  if (nextAttribute == 2) result = result + "   ";
                  if (nextAttribute == 3) result = result + "  ";
                  result += rate;
                  document.getElementById("dropDnRates").add(new Option(result, "Value" + (nextAttribute+1)));
                }
             }
         }
      </script>


</head>
<body style="width: 799px" onload="javascript:loadRates();">
    <form id="form1" runat="server">
    <div>

        <table>
            <tr>
 
                <td">
                     <table>
                        <tr>
                             <td>
                                 <select name="dropDnRates" id="dropDnRates" size="5" style="width: 254px; background-color: #00CCFF; color: #0000FF;" multiple="multiple"> </select>
                             </td>
                        </tr>
 
                    </table>
                </td>
             
            </tr>
        </table>
    </div>
       
    </form>
</body>

</html>


And here is the XML file:

<?xml version="1.0" encoding="utf-8" ?>
<PartialRates>
  <partialRates rate1="Argentina 1.6 cents" rate2="Brazil 2.4 cents" rate3="China 2.8 cents" rate4="India 3.5 cents" rate5="Russia 2.3 cents"></partialRates>
</PartialRates>
0
hieloCommented:
Instead of:
xmlDoc.getElementsByTagName("...")

try:
xmlDoc.responseXML.documentElement.getElementsByTagName("...")
0
prainAuthor Commented:
Ok. I tried. Now that line throws an exception for IE but OK for both Chrome and Firefox but with caveat. That is the values do not appear on the list box. However when I print the length using

alert("Length : " + itemsLength);

it prints the correct length.

I do not know however why it is not populating the listbox with the XML items (This issue is in Chrome and Firefox). I have to figure this out.

On IE as I said, the line you suggested is throwing an exception. So I have to go by the original line when the browser is IE. I can live with that.
0
hieloCommented:
>>Now that line throws an exception for IE
Then change it to:
if( window.ActiveXObject )//IE
{
  xmlDoc.getElementsByTagName("...")
}
else
{
  xmlDoc.responseXML.documentElement.getElementsByTagName("...")
}

>>I do not know however why it is not populating the listbox with the XML items (This issue is in Chrome and Firefox). I have to figure this out.
But I already figured the reason for this for you.

Like I said in post ID: 39525366, you are working with two different utilities:
Microsoft.XMLDOM which has its own list of properties and methods which are DIFFERENT from the properties and methods of XMLHttpRequest.  On the code you pasted, I see ".getNamedItem()", which does not exist in XMLHttpRequest().

Note: I suspect your project would be greatly simplified if you dropped support for IE6 and stick with IE7+ which means that your focus would be only on XMLHttpRequest object.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
prainAuthor Commented:
OK Thanks for the support. I have fixed all problems and works in all major browsers.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Scripting Languages

From novice to tech pro — start learning today.