3

I have this ajax javascript code that calls a servlet to retrieve two values (firstname, telephone). I know how to get a single value but not multiple values from the servlet.

Here's my ajax

    <script>
        function getCustomerDetailsAjax(str) {
            str = $('#customerId').val();

            if (document.getElementById('customerId').value <= 0) {
                document.getElementById('firstName').value = " ";
                document.getElementById('telephone').value = " ";
                document.getElementById('vehicleMake').value = " ";
                document.getElementById('vehicleModel').value = " ";
                document.getElementById('vehicleColor').value = " ";
            } else {
                $.ajax({
                    url: "GetCustomerDetails",
                    type: 'POST',
                    data: {customerId: str},
                    success: function (data) {                       
                        alert(data); //I want to get 2 servlet values and alert them here. How can I do that?
                    }
                });
            }
        }
    </script>

And this is my servlet

public class GetCustomerDetails extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out=response.getWriter();
    int customerId = Integer.valueOf(request.getParameter("customerId"));
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
        PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
        ps.setInt(1, customerId);
        ResultSet result=ps.executeQuery();
        if(result.next()){
            out.print(result.getString("firstname")); //I want to send this value
            out.print(result.getString("telephone")); //and this value

        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    }

}

@Override
public String getServletInfo() {
    return "Short description";
}// </editor-fold>

}

This is the part that retrieves the data from the servlet,how to get multiple values from it and alert?

       success: function (data) {                       
            alert(data); //I want to get 2 servlet values and alert them here. How can I do that?
       }

Thank you!

4
  • Can someone please help me? Commented May 19, 2018 at 8:15
  • Hi. To share data between your web service and the client, you must choose a protocol/strategy that best fit your needs (XML, JSON...). Since you're using javascript, I recommend reading about JSON (stands for "JavaScript Object Notation"). In your example, you should generate and return a JSON String (with correct Content-type headers) - read about javax.json package. With JSON, you can return a data structure with the fields you choose. Commented May 19, 2018 at 8:15
  • @mrlew can you direct me to some examples please? a big help Commented May 19, 2018 at 8:21
  • I posted an answer. Hope it helps. Commented May 19, 2018 at 8:43

2 Answers 2

4

To share data between your web service and the client, you must choose a protocol/strategy that best fit your needs (XML, JSON...).

Since you're using JavaScript, I recommend reading about JSON (stands for "JavaScript Object Notation").

In your example, you should generate and return a JSON String (with correct Content-type headers) - you can read about the javax.json package. With JSON, you can return a data structure with the fields you choose.

Something like that (untested - it's been a long since I've coded Java):

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out=response.getWriter();
    int customerId = Integer.valueOf(request.getParameter("customerId"));
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
        PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
        ps.setInt(1, customerId);
        ResultSet result=ps.executeQuery();
        if(result.next()){

            /* set response content type header: jQuery parses automatically response into a javascript object */
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");

            /* construct your json */
            JsonObject jsonResponse = new JsonObject();
            jsonResponse.put("firstname", result.getString("firstname"));
            jsonResponse.put("telephone", result.getString("telephone"));            

            /* send to the client the JSON string */
            response.getWriter().write(jsonResponse.toString());
           // "{"firstname":"first name from db","telephone":"telephone from db"}"

        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    }

}

In your JS (I suppose you're using jQuery, because of the success callback):

   success: function (data) { 
        /* because you set the content-type header as 'application/json', you'll receive an already parsed javascript object - don't need to use JSON.parse. */


        console.log(data);
        /*
            {
                firstname: "first name from db",
                telephone: "telephone from db"
            }

        */

        alert(data.firstname); //alert firstname
        alert(data.telephone); //alert phone
   }
Sign up to request clarification or add additional context in comments.

Comments

0

Yeah you can do this with JSON, as the previous answer has already stated, but i'd just like to add that there are a couple things you can do to simplify your code further since you are using jquery.

   <script>
        function getCustomerDetailsAjax(str) {
            str = $('#customerId').val();

            if (str <= 0) {
                $('#firstName').val(" ");
                $('#telephone').val(" ");
                $('#vehicleMake').val(" ");
                $('#vehicleModel').val(" ");
                $('#vehicleColor').val(" ");
                $('#firstName').val(" ");
            } else {

          //with jquery you can do this, which is much easier.
          var params = {customerId: str}; //set paramaters
          $.post("GetCustomerDetails", $.param(params), function(responseJson) {
              //handle response
              var firstname = responseJson.firstname;
              var telephone = responseJson.telephone;

            //now do whatever you want with your variables

           });

            }

        }
    </script>

Also, some changes here:

public class GetCustomerDetails extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out=response.getWriter();
    int customerId = Integer.valueOf(request.getParameter("customerId"));
    try {
        Class.forName("com.mysql.jdbc.Driver");
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost/Vehicle", "root", "");
        PreparedStatement ps = con.prepareStatement("SELECT fistname,telephone FROM customers WHERE customerid=?");
        ps.setInt(1, customerId);
        ResultSet result=ps.executeQuery();
        if(result.next()){

        String firstname = result.getString(1); //firstname
        String telephone = result.getString(2); //telephone

        JsonObject jsonResponse = new JsonObject();
        jsonResponse.put("firstname", firstname);
        jsonResponse.put("telephone", telephone);   

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(jsonResponse.toString());

        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(GetCustomerDetails.class.getName()).log(Level.SEVERE, null, ex);
    }

}

There are other ways to send values from your servlet to your jsp/html page. I highly recommend checking out BalusC's answer here on How to use Servlets and Ajax, it's extremely helpful.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.