How to test your Ajax call using JSP

If you building the web app and want to test your Ajax call by calling the controller here is the snippet you can use.

[code language=”javascript”]
$(document).ready(function() {
$.ajax({
type: "GET",
url: "/YourControllerURL"
}).done(function(data) {
console.log(data);
});
});
[/code]

  1. place the snippet inside the tag inside JSP
  2. in chrome press F12 for developer tools in chrome.
  3. navigate to console tab
  4. in browser navigate to JSP with snippet code.

 

Alternatively, you can view the navigation tab inside the developer tools and see your ajax request and response from controller.

Sweetness of this approach compared to Postman, is that you don’t need to provide all the authorization details.

Note: for testing purpose change your controller to GET method

Note 2: great article to learn about Ajax methods:

https://learn.jquery.com/ajax/jquery-ajax-methods/

Also if you need to pass data to your controller you can use bellow snippet. It returns json, of course your controller must return json too.

[code language=”javascript”]

var data = {some data you need for your controller ex. id}
$(document).ready(function() {
$.ajax({
type: "GET",
url: "/YourControllerURL",
contentType: "application/json",
dataType: "json",
data:data
}).done(function (nameOfJsonControllerReturns){

console.log(nameOfJsonControllerReturns.data);

});
}); [/code]

Leave a Reply

Your email address will not be published. Required fields are marked *