There's a ton of these questions out there, but I am unable to find what is missing.
My JSP page:
<button onclick="testAjax1()">Test Ajax 1</button>
<button id="testAjax2">Test Ajax 2</button>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
// test 1
function testAjax1() {
$.ajax({
type: "GET",
url: "/ajax_test",
success: function(response){
console.log("Response for testAjax1: " + response);
},
error: function(e){
console.log("Error: " + e);
}
});
}
// test 2
$(document).on("click", "#testAjax2", function() {
$.get("/ajax_test", function(response) {
console.log("Response for testAjax2: " + response);
});
});
</script>
My JAX-RS endpoint:
import javax.servlet.http.HttpServletResponse;
@Context
protected HttpServletResponse response;
@GET
@Path("/ajax_test")
@Consumes("application/x-www-form-urlencoded; charset=UTF-8")
@Produces({ "text/html" })
public void testAjax() throws IOException {
System.out.println("/ajax_test reached");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("response from server");
}
I have confirmed that both buttons result in my backend method being called (i.e. "/ajax_test reached" is printed to my local host console).
However, the response data to my ajax functions are undefined (i.e. "Response for testAjax1: undefined" or "Response for testAjax2: undefined" are printed to my chrome console).
What am I doing wrong?