1

What I basically what to do is to read an ID from user, pass it to a servlet using AJAX and then fetch the corresponding book name and course from database and then display them in respective textboxes. AJAX is like rocket science to me and I have just started from some basic online tutorials. Here's the code I have written:

JSP code:

<body>
Edit book details:</br>
Enter Book Id: <input type="text" id="tb1" onkeyup="get(this.value)"/></br>
Book name is: <input type="text" id="tb2"/></br>
Course is: <input type="text" id="tb3"/></br>
</body>

JS code:

    <script>

    function get(str)
    {
        var xmlhttp=new XMLHttpRequest();
        xmlhttp.onreadystatechange=function()
          {
          if (xmlhttp.readyState==4 && xmlhttp.status==200)
            {
              document.getElementById("tb2").value=xmlhttp.responseText;
              document.getElementById("tb3").value=xmlhttp.responseText;
            }
          }
        xmlhttp.open("GET","Demo?q="+str,true);
        xmlhttp.send();

    }

    </script>

Servlet code:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String str=request.getParameter("q");

        String book,course;
        try
        {
                Class.forName("com.mysql.jdbc.Driver");
                Connection con=DriverManager.getConnection(url,user,pass);
                PreparedStatement ps=con.prepareStatement("select  bname,course from product where pid=?");
                ps.setString(1,str);
                ResultSet rs=ps.executeQuery();
                if(rs.next())
                {
                    book=rs.getString(1);
                    course=rs.getString(2);
                }
                else
                {
                    book="";
                    course="";
                }
                response.getWriter().write(book);
                response.getWriter().write(course);

        }
        catch(Exception e)
        {

            e.printStackTrace();
        }

    }

The problem is that the results are both shown in same textbox(upper screenshot) and I want it to be like the lower one.

Yes, I know the problem is that I am writing document.getElementById("tb2").value=xmlhttp.responseText; document.getElementById("tb3").value=xmlhttp.responseText;

And that's what I am asking, how do I filter the responseText according to requirements?screenshot

17
  • 1
    Serverside return json, something that looks like { book:'english', course:'6th standard'} and clientside do a var rec = JSON.parse(xmlhttp.responseText); document.getElementById("tb2").value = rec.book; document.getElementById("tb3").value = rec.course; see this Commented Jul 23, 2014 at 16:46
  • How do I return { book:'english', course:'6th standard'}? By setting this in a string? As you see I am pretty new to this. Commented Jul 23, 2014 at 17:05
  • You could also return a string where different fields are delimited by some reserved character and then use .split(delimChar) in javascript to split them into an array. Commented Jul 23, 2014 at 17:07
  • I would just build-up a string. I'm more new than you on this. I'm not a java/jsp dev at all.... If you got that running start looking for a tutorial on how to do JSON responses with jsp... Commented Jul 23, 2014 at 17:11
  • @rene : I wrote: String str="{ book:'english', course:'6th standard'}"; response.getWriter().write(str); in the servlet and var rec = JSON.parse(xmlhttp.responseText); document.getElementById("tb2").value = rec.book; document.getElementById("tb3").value = rec.course; in JS. But the textbox does not shows any values. Commented Jul 23, 2014 at 17:17

2 Answers 2

2

It looks like you actual problem is that you want to pass two strings (the book name and the course) in a single AJAX response, but you don't know how to separate them in you JavaScript code.

If so, the answer is to use the .split() method, e.g. like this:

// assumes that the strings are separated by line breaks ("\n")
var lines = xmlhttp.responseText.split("\n");
document.getElementById("tb2").value = lines[0];
document.getElementById("tb3").value = lines[1];

Of course, to make this work, in your Servlet you need to ensure that the two strings are in fact separated by newlines, either by explicitly writing a "\n" between them or by using .writeln(). You also need to make sure that none of the strings themselves can even contain a newline; for your data, that seems likely, but you ought to check it anyway.

If you wish to pass more complicated data back from your Servlet, the standard format for that is JSON. In your Servlet, you can encode your data into JSON using a library like JSON.simple, while in JavaScript, at least in modern browsers, you can use the built-in JSON parser, e.g. like this:

// assumes that the response is JSON, e.g.:
// { book: "English", course: "6th standard" }
var data = JSON.parse( xmlhttp.responseText );
document.getElementById("tb2").value = data.book;
document.getElementById("tb3").value = data.course;

The main advantage of using JSON, besides the ability to transmit more complex data structures, is that if you use a proper JSON library to generate it, you can pass arbitrary strings without having to worry about whether they, say, contain newlines or not.


I would also like to make a few more suggestions. One is not to use XMLHttpRequest directly, but to instead use a library like jQuery that provides a more convenient interface. Using jQuery, your entire client-side code (assuming the server returns JSON) can be simplified to just:

$('#tb1').on( 'keyup', function () {
   $.ajax( {
      url: 'Demo',                 // URL of Servlet
      data: { q: this.value },     // parameters to Servlet
      dataType: 'json',            // type of data to expect back

      success: function ( data ) {
          $('#tb2').val( data.book );
          $('#tb3').val( data.course );
      }
   } );
} );

or, if your server returns plain text with, say, newline separators:

$('#tb1').on( 'keyup', function () {
   $.ajax( {
      url: 'Demo',
      data: { q: this.value },
      dataType: 'text',

      success: function ( text ) {
          var lines = text.split( "\n" );
          $('#tb2').val( lines[0] );
          $('#tb3').val( lines[1] );
      }
   } );
} );

Note that this code directly attaches the keyup handler via jQuery (since that's considered good style), so you don't need the onkeyup="get(this.value)" attribute in your HTML. It also fixes a bunch of bugs in your original code, like the fact that you forgot to URL-encode the q parameter value.

The other suggestion, which I already made on meta.SE, is that you might want to spend some time learning to walk (e.g. how to use .split() and JSON) before trying to run (e.g. writing Servlets to return data via AJAX). For that, a few hours with good introductory tutorial to Java and JavaScript may be more useful than a dozen questions on Stack Overflow.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks I'll try the code. and for "before trying to run (e.g. writing Servlet.." I was working on servlets with this thing but thought using AJAX for this would yield better results.Saw A bunch of ajax tutorials and wrote the code.I also Searched this thing but didn't found any relevant results. I didn't knew that json is used this way. I am not a professional coder or something, just a college student. Still learning things..
2

To use the string split method I suggested.

In your servlet (comma can be replaced by whatever you want):

response.getWriter().write(book+","+course);

This, of course, assumes you have reserved comma for use as the separator and there's no way it would be in your varaibles book or course.

In your javascript:

var responseArray = xmlhttp.responseText.split(",");
var book   = responseArray[0];
var course = responseArray[1];

To use JSON (at its simplest), in your servlet:

response.getWriter().write("{ book:'"+book+"', course:'"+course+"'}");

You can of course use java json library to do it better. If your variables book and course used the characters ', "", {, or } inside them, for instance, you would need to encode them or it would break the Json. See, for example, https://code.google.com/p/json-simple/wiki/EncodingExamples

In your javascript:

var jsonObj = JSON.parse(xmlhttp.responseText);
var book   = jsonObj.book;
var course = jsonObj.course;

7 Comments

Thanks for the answer I'll just try what you have written.
I updated the function as: function getit(str) { var xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { var jsonObj = JSON.parse("xmlhttp.responseText"); var book = jsonObj.book; var course = jsonObj.course; document.getElementById("tb2").value=book; document.getElementById("tb3").value=course; }} xmlhttp.open("GET","Demo?q="+str,true); xmlhttp.send(); } The console is showing an error: Uncaught SyntaxError: Unexpected token x
@Nivedita, Try just going to the page you call in ajax (i.e. Demo?q=whatever) by going in the address bar. Then view source. Is there an extraneous x in there?
fine i'll just try that and report back here
I wrote http://localhost:8087/ajax/Demo?q=2 in the address bar and got {book:Geography,course:6th standard}. Actually earlier I was getting the error with b written in place of x so I wrote "xmlhttp.responseText" (double quotes) in JSON.parse. Any idea?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.