Hi friends,

i have a problem in ajax.The code will get values when i use IE but it doesnt work with mozilla browser.It showing the alert message ? I am adding the code along with this.Expecting the reply soon.

var xmlHttp;

function getXmlHttp()
{ 
try {
    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");     
    } 
    catch (e) 
    {
        try { 
              xmlHttp=new XMLHttpRequest(); 
            }  
        catch (e)
            {
                try {                                        
                    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                    } 
                catch (e)
                    {
                    alert("Please use a new browser!"); 
                    return false;
                    } 
            } 
    }  
}
function user() 
{
  document.getElementById('form').style.visibility = "visible";
  var id=document.getElementById('id').value;    
  getXmlHttp();  
  var myurl = "<%=request.getContextPath()%>/AjaxUser.do?type=ajax&id="+id;  
  xmlHttp.open("GET", myurl , true);  
  xmlHttp.onreadystatechange = useHttpResponseSuggestId;
  xmlHttp.send(null);  
}
function useHttpResponseSuggestId()
{ 

 if (xmlHttp.readyState == 4) 
  {     
    if(xmlHttp.status == 200) 
    {
    var textout = xmlHttp.responseText;     
        try
        { 
                    var x= new DOMParser().parseFromString(textout, 'text/xml');                         
                    xmldom.async="false";    
                    xmldom.loadXML(x);       
                    alert(xmldom);
            xmlObj=xmldom.documentElement;
                    var master = [document.getElementById('name'),document.getElementById('password'),
                            document.getElementById('realname'),document.getElementById('email'),
                            document.getElementById('title'),document.getElementById('desc')]; 
                            var length=xmlObj.childNodes.length;                             
                            for(var i=0;i<master.length;i++)
                            {
                            master[i].value = xmlObj.childNodes[i].firstChild.nodeValue;
                            }  
        }
        catch(e)
        {
            try
            {
                            var xmldom = new ActiveXObject('Microsoft.XMLDOM');                                
                            xmldom.async="false";                                 
                xmldom.loadXML(textout);                             
                xmlObj=xmldom.documentElement;                             
                            var master = [document.getElementById('name'),document.getElementById('password'),
                            document.getElementById('realname'),document.getElementById('email'),
                            document.getElementById('title'),document.getElementById('desc')]; 
                            var length=xmlObj.childNodes.length;                             
                            for(var i=0;i<master.length;i++)
                            {
                            master[i].value = xmlObj.childNodes[i].firstChild.nodeValue;
                            }                                      
                        }
            catch(e)
            {
                alert("Please use a new browser! This browser does not support XML!");        
            }
        }
    }

 }
}

i am getting this alert("Please use a new browser!");
while using mozilla....

Edited 3 Years Ago by mike_2000_17: Fixed formatting

Check to see if any of the methods or functions you are using are nonstandard IE extensions to JS. Other browsers can't use them.

Can't see why your codes doesn't invoke xmlHttp=new XMLHttpRequest(); bit odd.

var xmlHttp;
function getXmlHttp()
{
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
try {
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
alert("Please use a new browser!");
return false;
}
}
}
}

Just a suggestion:

What you want to do when creating an XMLHttpRequest() Object is to test for the W3C implementation before IE6 and older implementation. The reason is that IE7 still supports the IE6 XHR object which is created via ActiveX.

Simple example to replace the code above. See if it works:

xmlHttp=null;
function getXmlHttp() {

xmlHttp=null;
// code for Mozilla, etc.
if (window.XMLHttpRequest)
  {
  xmlHttp=new XMLHttpRequest();
  }
// code for IE
else if (window.ActiveXObject)
  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
else alert("Please use a new browser!");
return xmlHttp;
}

ref: http://www.w3schools.com/xml/xml_http.asp

Actually the problem may be in this code

if(xmlHttp.status == 200)
{
var textout = xmlHttp.responseText;
try
{
var x= new DOMParser().parseFromString(textout, 'text/xml');
xmldom.async="false";
xmldom.loadXML(x);
alert(xmldom);
xmlObj=xmldom.documentElement;
var master = [document.getElementById('name'),document.getElementById('password'),
document.getElementById('realname'),document.getElementById('email'),
document.getElementById('title'),document.getElementById('desc')];
var length=xmlObj.childNodes.length;
for(var i=0;i<master.length;i++)
{
master.value = xmlObj.childNodes.firstChild.nodeValue;
}
}

I am getting the textout value as xml in IE but didnt get the values in Mozilla browser

Actually the problem may be in this code

if(xmlHttp.status == 200)
{
var textout = xmlHttp.responseText;
try
{
var x= new DOMParser().parseFromString(textout, 'text/xml');
xmldom.async="false";
xmldom.loadXML(x);
alert(xmldom);
xmlObj=xmldom.documentElement;
var master = [document.getElementById('name'),document.getElementById('password'),
document.getElementById('realname'),document.getElementById('email'),
document.getElementById('title'),document.getElementById('desc')];
var length=xmlObj.childNodes.length;
for(var i=0;i<master.length;i++)
{
master.value = xmlObj.childNodes.firstChild.nodeValue;
}
}

I am getting the textout value as xml in IE but didnt get the values in Mozilla browser

Good Call.

You should use

var textout = xmlHttp.responseXML;

instead of

var textout = xmlHttp.responseText;

and remove the DOMParser() functions.

You have to either make sure your server sends the correct XML headers when serving the response.

eg in PHP:

header('Content-Type: text/xml');

OR you can force the browser to treat the response as XML.

xmlHttp.overrideMimeType('text/xml');

Then the XML document will be available for traversal/manipulation using DOM Interface.

You can also replace:

var x= new DOMParser().parseFromString(textout, 'text/xml');
xmldom.async="false";
xmldom.loadXML(x);
alert(xmldom);
xmlObj=xmldom.documentElement;

with:

var xmldom = new DOMParser().parseFromString(textout, 'text/xml');
xmlObj=xmldom.documentElement;

this is the correct usage of DOMParser().

It is however still better for you to get the XMLHttpRequest response as XML instead of the way it is done in your example where you are retrieving it as Text and then using browser specific XML/DOM parsers to convert the text to XML.

The problem is again in mozilla browser

Below is my index.jsp page in that i written the script of ajax

var xmlHttp;

function getXmlHttp()
{ 

    try 
    {
        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");     
    } 
    catch (e) 
    {
        try { 
              xmlHttp=new XMLHttpRequest(); 
            }  
        catch (e)
            {
                try {                                        
                    xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                    } 
                catch (e)
                    {
                    alert("Please use a new browser!"); 
                    return false;
                    } 
            } 
    }  
}


        function ajax()
        {
        var name=document.getElementById('name').value; 
        getXmlHttp();
        var myurl="<%=request.getContextPath()%>/AjaxController?type=ajax&name="+name; 
        alert(myurl);
        xmlHttp.open("GET", myurl , true);  
        xmlHttp.onreadystatechange = useHttpResponseSuggestId;
        xmlHttp.send(null);  
        }

    function useHttpResponseSuggestId()
      { 
     if (xmlHttp.readyState == 4) 
        {     
         if(xmlHttp.status == 200) 
            {
            var textout = xmlHttp.responseText;     
            alert(textout);
            try
        { 
                    var xmldom = new DOMParser().parseFromString(textout, 'text/xml');
                    xmlObj=xmldom.documentElement;
                    var master = document.getElementById('ajaxname');
                    master.value=xmlObj.childNodes[0].firstChild.nodeValue;  
                    }
        catch(e)
        {
            try
            {
                            var xmldom = new ActiveXObject('Microsoft.XMLDOM');                                
                            xmldom.async="false";                                 
                xmldom.loadXML(textout);                             
                xmlObj=xmldom.documentElement;                             
                            var master = document.getElementById('ajaxname');
                            master.value = xmlObj.childNodes[0].firstChild.nodeValue;                         
                        }
            catch(e)
            {
                alert("Please use a new browser! This browser does not support XML!");        
            }
        }
            }
        }
     }

Edited 3 Years Ago by pyTony: fixed formatting

its calling the ajaxcontroller.java file which was written below

AjaxController.java

public class AjaxController extends HttpServlet {

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {       
        response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
        System.out.println("/Ajax Controller");
        PrintWriter out = response.getWriter();
        out.println("<?xml version=\"1.0\"?>"); 
        out.println("<code>");
        out.println("<name>sree</name>");  
        out.println("</code>");        
        out.close();
        out.flush();
        response.flushBuffer();       
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
    // </editor-fold>
}

Edited 3 Years Ago by pyTony: fixed formatting

Problem is when i run this code in IE it works fine.It takes the second try method in the index.jsp
When it comes to mozilla it throws an exception from the first try method as "Please use a new browser! This browser does not support XML!"

so can u help me please

Problem is when i run this code in IE it works fine.It takes the second try method in the index.jsp
When it comes to mozilla it throws an exception from the first try method as "Please use a new browser! This browser does not support XML!"

so can u help me please

Do you have firebug installed on Firefox?

Try viewing your XMLHttpRequest in Firebug and seeing if the response is well formatted.
What version of FF is it btw?

You can also tell if its well formatted or not by testing for the existence of xmlHttp.responseXML.

You should really be using xmlHttp.responseXML anyway, since any browser supporting XMLHttpRequest will support the responseXML property.

I am getting the response from firebug

<?xml version="1.0"?>

<code>

<name>sree</name>

</code>

but i didnt get the value

i am getting the textout value as above stated response.After that two try blocks are their.In IE the second try block is executing but in mozilla it enters in both the try block but returns exception ? what will be the reason for that

Try removing the different DOM parsing functions and just have XMLHttpRequest return XML.

function ajax()
{
var name=document.getElementById('name').value;
getXmlHttp();
var myurl="<%=request.getContextPath()%>/AjaxController?type=ajax&name="+name;
alert(myurl);
xmlHttp.open("GET", myurl , true);
xmlHttp.onreadystatechange = useHttpResponseSuggestId;
xmlHttp.send(null);
}

function useHttpResponseSuggestId()
{
if (xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
var textout = xmlHttp.responseText;
alert(textout);

var xmlObj = xmlHttp.responseXml.documentElement;

var master = document.getElementById('ajaxname');
master.value=xmlObj.childNodes[0].firstChild.nodeValue; 


}
}
}
function useHttpResponseSuggestId()
      { 
     if (xmlHttp.readyState == 4) 
        {     
         if(xmlHttp.status == 200) 
            {
            var textout = xmlHttp.responseText;     
            alert(textout);
            try
		{                 
                
                var xmlObj = xmlHttp.responseXml.documentElement;
                var master = document.getElementById('ajaxname');
                master.value=xmlObj.childNodes[0].firstChild.nodeValue; 
                alert(master.value);
              }
		catch(e)
		{
			try
			{
                        alert("hi1234");
                            var xmldom = new ActiveXObject('Microsoft.XMLDOM');                                
                            xmldom.async="false";                                 
			    xmldom.loadXML(textout);                             
			    xmlObj=xmldom.documentElement;	                           
                            var master = document.getElementById('ajaxname');
                            master.value = xmlObj.childNodes[0].firstChild.nodeValue;                         
                        }
	     	catch(e)
	     	{
		     	alert("Please use a new browser! This browser does not support XML!");        
	     	}
		}
            }
        }
     }

after your suggestion i tried this code buy it doesnt work with mozilla again ?

It again doesn't work ?

var xmlObj = xmlHttp.responseXML.documentElement;
                alert(xmlObj);

i put this alert message.when explorer it displays [Object] and in Mozilla it displays [Object element]

after this code i put

master.value=xmlObj.childNodes[0].firstChild.nodeValue; 
                alert(master.value);

then this alert is not working i think this makes an exception ?

It again doesn't work ?

var xmlObj = xmlHttp.responseXML.documentElement;
                alert(xmlObj);

i put this alert message.when explorer it displays [Object] and in Mozilla it displays [Object element]

after this code i put

master.value=xmlObj.childNodes[0].firstChild.nodeValue; 
                alert(master.value);

then this alert is not working i think this makes an exception ?

Yes, the exception occurs at

master.value=xmlObj.childNodes[0].firstChild.nodeValue;

it seems.

In your catch block place an

alert(e);

So we can see what the exception is.

yea the exception was

TypeError : xmlObj.childNodes[0].firstChild has no properties

You have got to realize that when we talk of XML, the whitespaces in your document matter and they get counted as a "#text" node. Assuming that xmlObj has the reference of the root node of the document, something like alert(xmlObj.childNodes[1].firstChild.nodeValue); should do the trick.

Here:

xmlObj -> <code> (Element)
childNodes[0] -> Whitespace (Text Node)
childNodes[1] -> <name> (Element)
firstChild -> sree (Text node)
nodeValue -> sree

Assuming the XML file is:

<?xml version="1.0" standalone="yes"?>
<code>
    <name>sree</name>
</code>

You have got to realize that when we talk of XML, the whitespaces in your document matter and they get counted as a "#text" node. Assuming that xmlObj has the reference of the root node of the document, something like alert(xmlObj.childNodes[1].firstChild.nodeValue); should do the trick.

Here:


Assuming the XML file is:

<?xml version="1.0" standalone="yes"?>
<code>
    <name>sree</name>
</code>

I'd suggest making sure you don't have any whitespace in your XML. That way, you don't need to have to cater for text nodes where you don't want them.

It may also be better to traverse the XML nodes, instead of selecting 'blindly', unless you are 100% sure the XML structure will not change.

eg: to get first non-text child

function getFirstChildTag(Node) {
var len = Node.childNodes.length;
for (var i = 0; i < len; i++)
   if (Node.childNodes[i].nodeName != '#text') return Node.childNodes[i];
}
master.value = getFirstChildTag(xmlObj).firstChild.nodeValue;

or use DOM methods such as getElementsByTagName() so that you're sure you're getting only what you want.

master.value=xmlObj.getElementsByTagName('name')[0].firstChild.nodeValue

If selecting 'blindly', test for the existence of each parent node first, then fallback if it doesn't exist.

eg:

if (xmlObj && xmlObj.childNodes ... etc
else ... etc

Of course, running a while loop till I get what I want or picking up elements based on their tag name is how I normally do things. I just wanted to let the OP know where he had made a mistake.

Of course, running a while loop till I get what I want or picking up elements based on their tag name is how I normally do things. I just wanted to let the OP know where he had made a mistake.

Was aiming that at OP and the DOM universe in general.. :)

You have got to realize that when we talk of XML, the whitespaces in your document matter and they get counted as a "#text" node. Assuming that xmlObj has the reference of the root node of the document, something like alert(xmlObj.childNodes[1].firstChild.nodeValue); should do the trick.

Here:


Assuming the XML file is:

<?xml version="1.0" standalone="yes"?>
<code>
    <name>sree</name>
</code>

thanks a lot it worked fine.........

This question has already been answered. Start a new discussion instead.