1

I'm trying to send the username to the servlet through an ajax call to check its availability, but the servlet show a null pointer exception.

I've also tried with the XMLHttpRequest instead of $.ajax.

This is my Javascript file:

$(document).ready(function() {
  $("#reg-form").submit(function() {
    var res = true;

    if (!testUser()) {
      res = false;
      $("#erruser").css("display", "block");
      $("#username").addClass("errclass");
    } else {
      $("#erruser").css("display", "none");
      $("#username").removeClass("errclass");
    }

    return res;
  });
});

function testUser() {
  var el = $("#username").val();
  var b = false;

  $.ajax({
    type: "POST",
    url: "CheckUserServlet",
    data: { user: el },
    dataType: "json",
    success: function(bool) {
      alert(bool);
      if (bool == "si") b = true;
    },
    error: function() {
      alert("errore");
    }
  });

  return b;
}

This is my servlet doPost method:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String username=request.getAttribute("user").toString();

    System.out.println("username servlet= "+username);

    response.setContentType("text/plain");
    response.setCharacterEncoding("UTF-8");

    if (!ud.doRetrieveByUser(username)) {
        response.getWriter().write("si");

        return;
    }

    response.getWriter().write("no");

    return;
}

Thanks!

Tobias Tengler
  • 6,848
  • 4
  • 20
  • 34
sfale
  • 210
  • 1
  • 10
  • 1
    Need to understand that ajax is ***asynchronous***. You can't do `if(!testUser())`. The request will not complete before the `return`. See [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – charlietfl Jul 16 '19 at 17:43
  • i've also tried to add async:false but nothing – sfale Jul 16 '19 at 17:46
  • Never ever use `async:false`. It is horrible practice and is deprecated – charlietfl Jul 16 '19 at 17:47
  • Start by inspecting the actual request in browser dev tools to see what is actually being sent – charlietfl Jul 16 '19 at 17:49
  • yes, i know. It was only for test, but in every way the servlet return an exception for null pointer – sfale Jul 16 '19 at 17:50
  • this is the error for the ajax call in browser dev tools `POST http://localhost/PhoneWorld/CheckUserServlet 500 send @ jquery.min.js:4 ajax @ jquery.min.js:4 testUser @ validationReg.js:63 (anonymous) @ validationReg.js:6 dispatch @ jquery.min.js:3 q.handle @ jquery.min.js:3` – sfale Jul 16 '19 at 17:53
  • 1
    You need to used `request.getParameter("user");` instead of `request.getAttribute("user").toString();` to get value of `user` , Also you are returning `plain text` from server but you have given `dataType: "json"` in ajax call change that as well . – Swati Jul 16 '19 at 17:53
  • thanks @Swati now the servlet does not return an exception of null pointer. I've deleted dataType from the ajax call and the type of return from servlet and now it seems to work bit only with `async:false` – sfale Jul 16 '19 at 18:03
  • You should considering chaining the functions. Call to check user through ajax and on success call the function to submit the form. – Subir Kumar Sao Jul 16 '19 at 18:55

1 Answers1

0

CLIENT SIDE

Your test user function will always return false regardless of if the server is operating correctly because $.ajax() is an async function. There are a few ways around this. In your case, without knowing much more about what you are building, I would suggest removing the return value from your test user function, and moving your logic into the success/failure areas in the ajax callback. This way, the ajax call just does it's thing and lets the success function modify your page however you want.

function testUser() {
  var el = $("#username").val();

  $.ajax({
    type: "POST",
    url: "CheckUserServlet",
    data: { user: el },
    dataType: "json",
    success: function(bool) {
      alert(bool);
      // put logic here
      if (bool === "si") {
        $("#erruser").css("display", "block");
        $("#username").addClass("errclass");
      } else {
        $("#erruser").css("display", "none");
        $("#username").removeClass("errclass");
      }
    },
    error: function() {
      alert("errore");
    }
  });
}

I would also suggest setting up the initial state of your page so that while this request is happening the user is shown something that makes sense. Answer the following question: "what do I show my users when the page does not know yet if it is a test user" and then set the initial state of the page accordingly

SERVER SIDE

I've always found interacting with java & JSON data a bit clunky, and your issue seems like something I've grappled with in the past.

Your question is "why is ajax sending null to the server". It may seem like that but what is really happening is that your server doesn't understand how to interpret the data it is getting. Take a look at this question about getting a JSON payload.. You need to tell your server how to parse the data coming from the client. If you were to inspect the data being sent, I would expect it looks something like this {"user":"blablabla"}.

If you have a class definition already, use that. For this I am using something that looks like this:

public class UserRequest {
    String user;
}
// get the body as a string. Requires https://commons.apache.org/proper/commons-io/
String body = IOUtils.toString(request.getReader())

// parse the json with gson. Requires https://github.com/google/gson
Gson g = new Gson();
User u = g.fromJson(body, UserRequest.class);
String username = u.user;
Landon
  • 144
  • 1
  • 5