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

user63762453
  • 1,734
  • 2
  • 22
  • 44
  • 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) – rene Jul 23 '14 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. – user63762453 Jul 23 '14 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. – developerwjk Jul 23 '14 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... – rene Jul 23 '14 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. – user63762453 Jul 23 '14 at 17:17
  • @developerwjk : I am new to all this.I don't know about how to use `.split(delimChar)` – user63762453 Jul 23 '14 at 17:18
  • Hit F12 in the browser and set a breakpoint on JSON.parse. check what is in xmlhttp.responseText and if you step over one line what the value of rec is. – rene Jul 23 '14 at 17:23
  • bdw The console has an error: `Uncaught SyntaxError: Unexpected token b ` What's that for? – user63762453 Jul 23 '14 at 17:26
  • That is an error in you javascript. Fix that first... – rene Jul 23 '14 at 17:35
  • fix the jsp to generate this string: `{ "book":"hello", "course":"c" }` – rene Jul 23 '14 at 17:43
  • The error was not there earlier. – user63762453 Jul 23 '14 at 17:43
  • Do I need to include any additional jars for json? I have json-lib-2.4-jdk15.jar – user63762453 Jul 23 '14 at 17:46
  • Here is a fiddle to experiment what works client side: http://jsfiddle.net/arSD2/1/ – rene Jul 23 '14 at 17:46
  • I wrote: `var text="{ book:'book', course:'course'}"; var obj = JSON.parse(text); document.getElementById("tb2").value=obj.book; document.getElementById("tb3").value=obj.course;` But the textboxes are still blank – user63762453 Jul 23 '14 at 17:55
  • Thanks for the fiddle. I will just check that – user63762453 Jul 23 '14 at 17:55
  • Fiddle working but when I copy those lines in my jsp file nothing happens. :( – user63762453 Jul 23 '14 at 18:16
  • I Even tried writing just: ` Edit book details: Enter Book Id: Book name is: Course is: ` does not works on browser but works in your fiddle. I tried in chrome and firefox – user63762453 Jul 23 '14 at 18:25

2 Answers2

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;
developerwjk
  • 8,619
  • 2
  • 17
  • 33
  • Thanks for the answer I'll just try what you have written. – user63762453 Jul 24 '14 at 14:04
  • 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` – user63762453 Jul 24 '14 at 14:58
  • @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? – developerwjk Jul 24 '14 at 19:28
  • fine i'll just try that and report back here – user63762453 Jul 25 '14 at 12:50
  • 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? – user63762453 Jul 25 '14 at 13:09
  • @Nivedita, If you put xmlhttp.responseText in double quotes like that then its trying to parse the literal string `"xmlhttp.responseText"` as json. – developerwjk Jul 25 '14 at 17:22
  • I solved the error.Removed the quotes and removed the parse statement. Read somewhere that the arises when you try to parse the already parsed JSON object. But I am getting undefined in the textboxes now. – user63762453 Jul 26 '14 at 09:27
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.

Community
  • 1
  • 1
Ilmari Karonen
  • 49,047
  • 9
  • 93
  • 153
  • 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.. – user63762453 Jul 24 '14 at 14:03