Error in Java or javascript (ajax)

Hi,

I tried to send variable from servlet to javascript. I tried to send it as xml or text but each time I have this error:

XML Parsing Error: junk after document element
Location: http://localhost:8080/TrackingSystem/controller?action=newPosition
Line Number 1, Column 40:<latitude>54.289182000000004</latitude><lognitude>18.462533999999998</lognitude>

response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
 
Then I tried following line of code:
 
 response.getWriter().write("<latitude>" + tracker.getLatitude() + "</latitude>");
or 
response.getWriter().write("zzzz");
 
in both ceases I got this error.

Open in new window

Lucinda08Asked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
objectsConnect With a Mentor Commented:
does your current servlet do anything required by the jsp or does it just generate the xml?

0
 
Gibu GeorgeChief Technology OfficerCommented:
Hello Lucinda08,
Please post the javascript  you used for parsing.


Regards,

gibu_george
0
 
Lucinda08Author Commented:


<script type="text/javascript"> 
var httpRequest;
alert('hello');
function getProfile()
{ alert('hello');
    var url = 'controller?action=newPosition';
 
    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("POST", url, true);
    httpRequest.onreadystatechange = function() {processRequest(); } ;
    httpRequest.send(null);
    
}
 
function processRequest()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
        {
            //get the XML send by the servlet
           var profileXML = httpRequest.responseXML.getElementsByTagName("longitude")[0];
			//var profileXML = httpRequest.responseText;
 
            var profileXML1 = httpRequest.responseXML.getElementsByTagName("latitude")[0];
            
            //Update the HTML
            updateHTML(profileXML,profileXML1);
          
        }
        else
        {
            alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
 
 
    function updateHTML(profileXML,profileXML1)
    {
        //The node valuse will give actual data
        var profileText = profileXML.childNodes[0].nodeValue;
        var profileText1 = profileXML1.childNodes[0].nodeValue;
         
        //Create the Text Node with the data received
        var profileBody = document.createTextNode(profileText);
        var profileBody1 = document.createTextNode(profileText1);  
                
       
      var  ex='http://maps.google.com/staticmap?center=' + profileBody+ ','+profileBody1+'&zoom=14&size=512x512&maptype=roadmap\&markers='+profileBody+ ','+profileBody1+'&key=ABQIAAAAaPMjJjI0QdqOoupoiDClHhS_Ia4_o8yd5tFdFcBoaoR01iuymhR-m0O8rSRJKNQDLrGBYlUfI9Ksng&sensor=true';
        //document.getElementById("targetElement").innerHTML=ex;
       document.write('<img src="'+ex+'">');
            //Check if the TextNode already exist      
    } 
    
} 
 
</script> 

Open in new window

0
Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

 
Lucinda08Author Commented:
but I even don't get my jsp page
0
 
Gibu GeorgeChief Technology OfficerCommented:
there is a spelling mistake in your xml you are using lognitude create the xml but using longitude in the parsing code
0
 
Gibu GeorgeChief Technology OfficerCommented:
<latitude>54.289182000000004</latitude><lognitude>18.462533999999998</lognitude>

var profileXML = httpRequest.responseXML.getElementsByTagName("longitude")[0];
0
 
Lucinda08Author Commented:
Now I have this:
XML Parsing Error: junk after document element
Location: http://localhost:8080/TrackingSystem/controller?action=newPosition
Line Number 1, Column 40:<latitude>54.289182000000004</latitude><lognitude>18.462533999999998</lognitude>
It also says that only one the highest element is allowed in xml document, but I need to pass two, so how the code should look like in servlet and javascript?
0
 
Gibu GeorgeChief Technology OfficerCommented:
you need to modify the xml as

<root>
<latitude>54.289182000000004</latitude><lognitude>18.462533999999998</lognitude>
</root>
as it is a valid xml format
0
 
Gibu GeorgeChief Technology OfficerCommented:
no need to change the code
0
 
Lucinda08Author Commented:
I think it is still not passed to the javascript, cause the script is not invoked. I even don't get this : alarm('hello'); in:

<script type="text/javascript">
alarm('hello');
var httpRequest;
alarm('hello');
function getProfile()
{
    var url = 'controller?action=newPosition';

-------------------------------------------
 I have got this in the browser:


This XML file does not appear to have any style information associated with it. The document tree is shown below.
     

<root>
<latitude>54.289182000000004</latitude>
<lognitude>18.462533999999998</lognitude>
</root>

and my script is invoked like this:

<body id="targetElement" onload="setInterval(function(){
   getProfile();
   moreCalls();
}, 3000);">

So I still think it is not passed. What I supposed to do ?

0
 
Gibu GeorgeChief Technology OfficerCommented:
Can you post your jsp page as well, I think something is wrong in your jsp.
0
 
Lucinda08Author Commented:
This is my jsp, it contain this java script. This should be refresh at each 5 second that is why I use setInterval method.
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!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" />
<link rel="STYLESHEET" type="text/css" href="css/css.css" />
<title>Tracking system Ltd.</title>
</head>
 
<%@ include file="header.txt" %>
 
<script type="text/javascript"> 
var httpRequest;
 
function getProfile()
{ 
    var url = 'controller?action=newPosition';
 
    if (window.ActiveXObject)
    {
        httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else if (window.XMLHttpRequest)
    {
        httpRequest = new XMLHttpRequest();
    }
    
    httpRequest.open("POST", url, true);
    httpRequest.onreadystatechange = function() {processRequest(); } ;
    httpRequest.send(null);
    
}
 
function processRequest()
{
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
        {
            //get the XML send by the servlet
           var profileXML = httpRequest.responseXML.getElementsByTagName("longitude")[0];//var profileXML = httpRequest.responseText;
 
            var profileXML1 = httpRequest.responseXML.getElementsByTagName("latitude")[0];
            
            //Update the HTML
            updateHTML(profileXML,profileXML1);
          
        }
        else
        {
            alert("Error loading page\n"+ httpRequest.status +":"+ httpRequest.statusText);
        }
    }
 
 
    function updateHTML(profileXML,profileXML1)
    {
        //The node valuse will give actual data
        var profileText = profileXML.childNodes[0].nodeValue;
        var profileText1 = profileXML1.childNodes[0].nodeValue;
         
        //Create the Text Node with the data received
        var profileBody = document.createTextNode(profileText);
        var profileBody1 = document.createTextNode(profileText1);  
                
       
      var  ex='http://maps.google.com/staticmap?center=' + profileBody+ ','+profileBody1+'&zoom=14&size=512x512&maptype=roadmap\&markers='+profileBody+ ','+profileBody1+'&key=ABQIAAAAaPMjJjI0QdqOoupoiDClHhS_Ia4_o8yd5tFdFcBoaoR01iuymhR-m0O8rSRJKNQDLrGBYlUfI9Ksng&sensor=true';
        //document.getElementById("targetElement").innerHTML=ex;
       document.write('<img src="'+ex+'">');
            //Check if the TextNode already exist      
    } 
    
} 
 
</script> 
 
 
 
 
 <body id="targetElement" onload="setInterval(function(){
   getProfile();
   moreCalls();
}, 3000);"> 
 
 
 
 
 
</html>

Open in new window

0
 
Gibu GeorgeChief Technology OfficerCommented:
change the url to '<%=request.getContextPath()%>controller?action=newPosition'
0
 
Gibu GeorgeChief Technology OfficerCommented:
instead of
response.getWriter().write("<latitude>" + tracker.getLatitude() + "</latitude>");

response.getOutputStream().write("<root><latitude>54.289182000000004</latitude><longitude>18.462533999999998</longitude></root>");
0
 
Lucinda08Author Commented:
I  changed  this:
 var url = 'controller?action=newPosition';
to:  var url= '<%=request.getContextPath()%>controller?action=newPosition';

in jsp

but I cant change  this:
response.getWriter().write("<latitude>" + tracker.getLatitude() + "</latitude>");
to:
 response.getOutputStream().write("<root><latitude>54.289182000000004</latitude><longitude>18.462533999999998</longitude></root>");

because it give me error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)


Now I have this in browser:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
<latitude>54.289182000000004</latitude>
0
 
Gibu GeorgeChief Technology OfficerCommented:
you need to add a / before the controller
0
 
Lucinda08Author Commented:
I add this  but still have this:

This XML file does not appear to have any style information associated with it. The document tree is shown below.
     
<latitude>54.289182000000004</latitude>
0
 
objectsCommented:
this q is a duplicate, can you please close one of them so we know where to post comments


0
 
objectsCommented:
have you got the servlet working ok yet?

0
 
Lucinda08Author Commented:
ok I closed another one, post comments here.
0
 
objectsCommented:
so what is your servlet now returning now?
0
 
Lucinda08Author Commented:
Servlet is working, I think. Now I am able to invoke the javascript but It seems to me that this xml from servlet :

response.getWriter().write("<root><latitude>"+tracker.getLatitude()+"</latitude><lognitude>"+tracker.getLognitude()+"</lognitude></root>");
               
is not passed to javascript cause when I put  alert(profileXML); in here:
 
function processRequest()
{
   
    if (httpRequest.readyState == 4)
    {
        if(httpRequest.status == 200)
        {
           
            //get the XML send by the servlet
           var profileXML = httpRequest.responseXML.getElementsByTagName("longitude")[0];
           alert(profileXML);
            var profileXML1 = httpRequest.responseXML.getElementsByTagName("latitude")[0];
       
It return me null.
0
 
Lucinda08Author Commented:
Is there any way to pass this as a text instead of xml and then take retrieve this in javascript?
0
 
objectsCommented:
use:

alert(httpRequest.responseXML);

0
 
Gibu GeorgeChief Technology OfficerCommented:
yuo are till using httpRequest.responseXML.getElementsByTagName("longitude") instead of longitude which is in the xml
0
 
Gibu GeorgeChief Technology OfficerCommented:
lognitude in xml
0
 
Lucinda08Author Commented:
When I use  alert(httpRequest.responseXML); it returns: [object].

I correct spelling but still it doesn't return me anything.  
0
 
objectsCommented:
good, now try this:

alert(httpRequest.responseText);

(and check the spelling as gibu_george points out)

0
 
Lucinda08Author Commented:
I think it return whole code from jsp( see attachment)
message.jpg
0
 
objectsCommented:
that explains why you're not getting the lat/longs :)  
the request is getting mapped to your jsp, it should be mapped to the servlet

0
 
Lucinda08Author Commented:
So what I should change?
0
 
objectsCommented:
try specifying the full url

0
 
Lucinda08Author Commented:
I use this in java script, and and I  use this also in another links, so it is not correct?

var url = 'controller?action=newPosition';  
0
 
Gibu GeorgeChief Technology OfficerCommented:
what does the 'controller?action=newPosition'; do?, id it redirecting to a jsp?
0
 
Lucinda08Author Commented:
It it is code from the javascript in the jsp  and it should redirect to servlet to  doPost method:

public  void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       
        response.setContentType("text/html");
         PrintWriter out = response.getWriter();
         String cmd;
         cmd = request.getParameter("action");
       
         if (cmd != null) {
       
             if (cmd.equals("newPosition"))
             {
               response.setContentType("text/xml");
                response.setHeader("Cache-Control", "no-cache");
             ......................................
         response.getWriter().write("<root><latitude>"+tracker.getLatitude()+"</latitude>        <longitude>"+tracker.getLognitude()+"</longitude></root>");
             
               RequestDispatcher rd= request.getRequestDispatcher("/position.jsp");
                rd.forward(request, response);
                ..................

               

0
 
Gibu GeorgeChief Technology OfficerCommented:
you are having the ajax call from position.jsp itself rt? so you don't need to do the forward. remove that and the code will work fine
0
 
objectsCommented:
              RequestDispatcher rd= request.getRequestDispatcher("/position.jsp");
               rd.forward(request, response);

get rid of that, you don't want to be redirecting to your jsp.

0
 
Gibu GeorgeChief Technology OfficerCommented:
yes that is the part which I mentioned
0
 
Lucinda08Author Commented:
When I remove this part instead of my jsp (javascript)  I have xml in the browser:


This XML file does not appear to have any style information associated with it. The document tree is shown below.
     

<root>
<latitude>54.289182000000004</latitude>
<longitude>18.462533999999998</longitude>
</root>

0
 
Gibu GeorgeChief Technology OfficerCommented:
Use  response.getOutputStream()
instead of  response.getWriter()
0
 
Lucinda08Author Commented:
But this give error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)
0
 
Lucinda08Author Commented:
But this give error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)
0
 
Gibu GeorgeChief Technology OfficerCommented:
response.getWriter().write("<root><latitude>"+tracker.getLatitude()+"</latitude>        <longitude>"+tracker.getLognitude()+"</longitude></root>".getBytes());
0
 
Lucinda08Author Commented:
But this give error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)
0
 
Lucinda08Author Commented:
But this give error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)
0
 
Lucinda08Author Commented:
I changed to this:
response.getWriter().write("<root><latitude>"+tracker.getLatitude()+"</latitude>        <longitude>"+tracker.getLognitude()+"</longitude></root>".getBytes());

and now I have this error:

XML Parsing Error: no element found
Location: http://localhost:8080/TrackingSystem/controller?action=newPosition
Line Number 1, Column 84:<root><latitude>54.289182000000004</latitude><longitude>18.462533999999998[B@22d166

It also says that cannot see xml by the meand of xsl and that following tags are not closed:
</longitude></root>
0
 
Gibu GeorgeChief Technology OfficerCommented:
response.getOutputStream().write(""+tracker.getLatitude()+"        "+tracker.getLognitude()+"".getBytes());

see the getBytes()


0
 
Lucinda08Author Commented:
I used getBytes() but it still give me this error
0
 
Gibu GeorgeChief Technology OfficerCommented:
with getOutputStream()
0
 
Lucinda08Author Commented:
Ok  I used  getBytes() with getOutputStream()  but now I have this error    :

java.lang.IllegalStateException: getWriter() has already been called for this response
      org.apache.catalina.connector.Response.getOutputStream(Response.java:579)
      org.apache.catalina.connector.ResponseFacade.getOutputStream(ResponseFacade.java:183)
      
0
 
Gibu GeorgeChief Technology OfficerCommented:
java.io.OutputStream outStream=response.getOutputStream();
outStream.write("<root><latitude>"+tracker.getLatitude()+"</latitude>        <longitude>"+tracker.getLognitude()+"</longitude></root>".getBytes());
outStream.flush();
0
 
Lucinda08Author Commented:
Tried this but still error is the same.
0
 
Gibu GeorgeChief Technology OfficerCommented:
it is working for me with the hard coded values
0
 
Gibu GeorgeConnect With a Mentor Chief Technology OfficerCommented:
i mean I am using hard coded values for the longitude and latitude
0
 
Lucinda08Author Commented:
If I used hard coded values I got this error:

java.lang.IllegalStateException: getWriter() has already been called for this response
      org.apache.catalina.connector.Response.getOutputStream(Response.java:579)
0
 
Gibu GeorgeChief Technology OfficerCommented:
Please post your servlet code as well
0
 
Lucinda08Author Commented:


                   
public  void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	response.setContentType("text/html");
	PrintWriter out = response.getWriter();
	String cmd;
	cmd = request.getParameter("action");
	 if (cmd != null) {
	   if (cmd.equals("newPosition"))
	    	 {
	          response.setContentType("text/xml");
		  response.setHeader("Cache-Control", "no-cache");
                  Tracker position = tracker.getPosition("1");
                  String s = "<root><latitude>"+tracker.getLatitude()+"</latitude><longitude>"+tracker.getLognitude()+"</longitude></root>";
		        //System.out.println(s);
java.io.OutputStream outStream=response.getOutputStream();
		        outStream.write(s.getBytes());
		        outStream.flush();
				
				
	    	 }
	    		
	     }
.......................

Open in new window

0
 
objectsCommented:
> This XML file does not appear to have any style information associated with it. The document tree is shown below.

thats what you want :)

you're problem (as I think I mentioned in your previous question) is that you need one request to return your html, and another to return your jsp

having one servlet to handle both serves no purpose and just confuses the issue.

Have one servlet return your xml,
and another to return the html page (this may not even need to be a servlet and just map directly to your jsp)

0
 
Lucinda08Author Commented:
Can you give me an example, or some code?
0
 
objectsCommented:
you already have the code from what I can see you just need to separate the two pieces

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.