Solved

Error in Java or javascript (ajax)

Posted on 2009-05-05
60
362 Views
Last Modified: 2012-05-06
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

0
Comment
Question by:Lucinda08
  • 27
  • 22
  • 11
60 Comments
 
LVL 12

Expert Comment

by:Gibu George
ID: 24305004
Hello Lucinda08,
Please post the javascript  you used for parsing.


Regards,

gibu_george
0
 

Author Comment

by:Lucinda08
ID: 24305100


<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
 

Author Comment

by:Lucinda08
ID: 24305107
but I even don't get my jsp page
0
 
LVL 12

Expert Comment

by:Gibu George
ID: 24305885
there is a spelling mistake in your xml you are using lognitude create the xml but using longitude in the parsing code
0
 
LVL 12

Expert Comment

by:Gibu George
ID: 24305896
<latitude>54.289182000000004</latitude><lognitude>18.462533999999998</lognitude>

var profileXML = httpRequest.responseXML.getElementsByTagName("longitude")[0];
0
 

Author Comment

by:Lucinda08
ID: 24306592
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24306665
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24306668
no need to change the code
0
 

Author Comment

by:Lucinda08
ID: 24306938
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24307007
Can you post your jsp page as well, I think something is wrong in your jsp.
0
 

Author Comment

by:Lucinda08
ID: 24307102
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24307310
change the url to '<%=request.getContextPath()%>controller?action=newPosition'
0
 
LVL 12

Expert Comment

by:Gibu George
ID: 24307324
instead of
response.getWriter().write("<latitude>" + tracker.getLatitude() + "</latitude>");

response.getOutputStream().write("<root><latitude>54.289182000000004</latitude><longitude>18.462533999999998</longitude></root>");
0
 

Author Comment

by:Lucinda08
ID: 24307698
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24308575
you need to add a / before the controller
0
 

Author Comment

by:Lucinda08
ID: 24308691
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
 
LVL 92

Expert Comment

by:objects
ID: 24309767
this q is a duplicate, can you please close one of them so we know where to post comments


0
 
LVL 92

Expert Comment

by:objects
ID: 24310345
have you got the servlet working ok yet?

0
 

Author Comment

by:Lucinda08
ID: 24310393
ok I closed another one, post comments here.
0
 
LVL 92

Expert Comment

by:objects
ID: 24310627
so what is your servlet now returning now?
0
 

Author Comment

by:Lucinda08
ID: 24312827
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
 

Author Comment

by:Lucinda08
ID: 24312834
Is there any way to pass this as a text instead of xml and then take retrieve this in javascript?
0
 
LVL 92

Expert Comment

by:objects
ID: 24312867
use:

alert(httpRequest.responseXML);

0
 
LVL 12

Expert Comment

by:Gibu George
ID: 24312877
yuo are till using httpRequest.responseXML.getElementsByTagName("longitude") instead of longitude which is in the xml
0
 
LVL 12

Expert Comment

by:Gibu George
ID: 24312882
lognitude in xml
0
 

Author Comment

by:Lucinda08
ID: 24312995
When I use  alert(httpRequest.responseXML); it returns: [object].

I correct spelling but still it doesn't return me anything.  
0
 
LVL 92

Expert Comment

by:objects
ID: 24313044
good, now try this:

alert(httpRequest.responseText);

(and check the spelling as gibu_george points out)

0
 

Author Comment

by:Lucinda08
ID: 24313283
I think it return whole code from jsp( see attachment)
message.jpg
0
 
LVL 92

Expert Comment

by:objects
ID: 24313312
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
 

Author Comment

by:Lucinda08
ID: 24313334
So what I should change?
0
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 92

Expert Comment

by:objects
ID: 24313368
try specifying the full url

0
 

Author Comment

by:Lucinda08
ID: 24313522
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24313547
what does the 'controller?action=newPosition'; do?, id it redirecting to a jsp?
0
 

Author Comment

by:Lucinda08
ID: 24313625
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24313696
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
 
LVL 92

Expert Comment

by:objects
ID: 24313697
              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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24313727
yes that is the part which I mentioned
0
 

Author Comment

by:Lucinda08
ID: 24313943
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24314021
Use  response.getOutputStream()
instead of  response.getWriter()
0
 

Author Comment

by:Lucinda08
ID: 24314166
But this give error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)
0
 

Author Comment

by:Lucinda08
ID: 24314176
But this give error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)
0
 
LVL 12

Expert Comment

by:Gibu George
ID: 24314217
response.getWriter().write("<root><latitude>"+tracker.getLatitude()+"</latitude>        <longitude>"+tracker.getLognitude()+"</longitude></root>".getBytes());
0
 

Author Comment

by:Lucinda08
ID: 24314238
But this give error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)
0
 

Author Comment

by:Lucinda08
ID: 24314404
But this give error:
The method write(int) in the type OutputStream is not applicable for the arguments (String)
0
 

Author Comment

by:Lucinda08
ID: 24314494
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24314506
response.getOutputStream().write(""+tracker.getLatitude()+"        "+tracker.getLognitude()+"".getBytes());

see the getBytes()


0
 

Author Comment

by:Lucinda08
ID: 24315398
I used getBytes() but it still give me this error
0
 
LVL 12

Expert Comment

by:Gibu George
ID: 24315477
with getOutputStream()
0
 

Author Comment

by:Lucinda08
ID: 24315796
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24316475
java.io.OutputStream outStream=response.getOutputStream();
outStream.write("<root><latitude>"+tracker.getLatitude()+"</latitude>        <longitude>"+tracker.getLognitude()+"</longitude></root>".getBytes());
outStream.flush();
0
 

Author Comment

by:Lucinda08
ID: 24316534
Tried this but still error is the same.
0
 
LVL 12

Expert Comment

by:Gibu George
ID: 24316639
it is working for me with the hard coded values
0
 
LVL 12

Assisted Solution

by:Gibu George
Gibu George earned 200 total points
ID: 24316655
i mean I am using hard coded values for the longitude and latitude
0
 

Author Comment

by:Lucinda08
ID: 24316917
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
 
LVL 12

Expert Comment

by:Gibu George
ID: 24316943
Please post your servlet code as well
0
 

Author Comment

by:Lucinda08
ID: 24317333


                   
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
 
LVL 92

Expert Comment

by:objects
ID: 24320964
> 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
 

Author Comment

by:Lucinda08
ID: 24324577
Can you give me an example, or some code?
0
 
LVL 92

Expert Comment

by:objects
ID: 24332395
you already have the code from what I can see you just need to separate the two pieces

0
 
LVL 92

Accepted Solution

by:
objects earned 300 total points
ID: 24332533
does your current servlet do anything required by the jsp or does it just generate the xml?

0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now