Ajax success function

It is because Ajax is asynchronous, the success or the error function will be called later, when the server answer the client. So, just move parts depending on the result into your success function like that :

What exactly is Ajax request? Is it different from Servlet Request?

An Ajax call is an asynchronous request initiated by the browser that does not directly result in a page transition. A servlet request is a Java-specifc term (servlets are a Java specification) for servicing an HTTP request that could get a simple GET or POST (etc) or an Ajax request. An Ajax (“Asynchronous Javascript and … Read more