0

i have a username textbox that when a user input a name it takes that name and send to server and the server check if the username has not been taken by anybody else, if so i need to send back somedata and tell the client that the username has been taken else if it is not i need to turn the textbox border color to green, now i can do sending username value to server but i don't know how to send back and how to receive the sent data using jquery ajax.

here is my code:

client:

$(document).ready(function() {
$('#Registeration_Username_box').on('input', function() {
    postUsernameToServer();
});

function postUsernameToServer() {
  var formData = {
            'username': $('input[name=UserName]').val(),
          };
          // process the form
     $.ajax({
         type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
         url: '../dusernameavailable', // the url where we want to POST
         data: formData, // our data object
         dataType: 'json', // what type of data do we expect back from the server
         encode: true
     }).done(function(data) {
         console.log(data);
     });
}
});

servlet:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String str = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
System.out.println(str);
}
jacky
  • 199
  • 1
  • 4
  • 15

2 Answers2

0

Add success and error to your ajax

function postUsernameToServer() {
var formData = {
  'username': $('input[name=UserName]').val(),
};
// process the form
$.ajax({
  type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
  url: '../dusernameavailable', // the url where we want to POST
  data: formData, // our data object
  dataType: 'json', // what type of data do we expect back from the server
  encode: true,
  success: function(data) {
    //TODO make the box green or whatever your requirement is
  },
  error: function() {
    //TODO username already taken
  }
});
}
});

In servlet send appropriate response. You will need to send a response code other than 200 for ajax to consider it as an error from the server.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String str = request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
    System.out.println(str);
    //TODO - check if user name exists or not
   if(user name already exists){
      response.setProperty(response.HTTP_STATUS_CODE, "500"); 
      PrintWriter out = response.getWriter();
      out.println("error");
      out.close();
   }
   else{
      PrintWriter out = response.getWriter();
      out.println("success");
      out.close();
   }

} }

Harshul Pandav
  • 1,016
  • 11
  • 23
  • it says http_status_code cannot be resolved or is not a field error – jacky Aug 24 '16 at 22:24
  • Try `HttpServletResponse.SC_FORBIDDEN` or any other codes. Check here - https://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/http/HttpServletResponse.html – Harshul Pandav Aug 24 '16 at 22:33
  • i added success now it doesn't even send any text value to server – jacky Aug 24 '16 at 22:36
  • debug js or check in console for the error. – Harshul Pandav Aug 24 '16 at 22:38
  • i am getting no error – jacky Aug 24 '16 at 22:39
  • my bad client works fine but the server doesn't send no succes, i tried this "if(i!=0){ PrintWriter out = response.getWriter(); out.println("error"); out.close(); } else{ PrintWriter out = response.getWriter(); out.println("success"); out.close(); }" int i = 0; – jacky Aug 24 '16 at 22:42
  • in my client i have "success: function(response) { if(response.isUserNameAvailable == true) alert('hello'); else alert('error'); }" but i am getting no success alert box nor error – jacky Aug 24 '16 at 22:43
0

Add a success handler to your ajax call.

You can try something like below; where 'green' and 'red' are css classes you defined in your CSS file .

$.ajax({
             type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
             url: '../dusernameavailable', // the url where we want to POST
             data: formData, // our data object
             dataType: 'json', // what type of data do we expect back from the server
             encode: true,
             success: function(response) {
               if(response.isUserNameAvailable == true) 
                    $('input[name=UserName]').addClass('green');
               else 
                   $('input[name=UserName]').addClass('red');
             }
         }).done(function(data) {
             console.log(data);
         });
Arun
  • 13
  • 4
  • by adding a success: function , my ajax doesn't even send the data now, how is that so – jacky Aug 24 '16 at 22:35
  • you might need to set content type in server side response.setContentType("application/json"); – Arun Aug 24 '16 at 22:45
  • Put a breakpoint in chrome where you have if(response.isUserNameAvailable == true) and see if you getting response. – Arun Aug 24 '16 at 22:49
  • contentType: "application/json", success: function(response) { if(response.isUserNameAvailable == true) alert('hello'); else alert('error'); }, i get nor hello and nor error, – jacky Aug 24 '16 at 22:50
  • my server: "int i = 0; if(i!=0){ PrintWriter out = response.getWriter(); out.println("error"); out.close(); } else{ response.setContentType("application/json"); PrintWriter out = response.getWriter(); out.println("success"); out.close(); } " – jacky Aug 24 '16 at 22:50