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.

$(document).ready(function() {
$.ajax({
type: "GET", 
url: "/YourControllerURL"
}).done(function(data) {
console.log(data);
});
});
  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.


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); 

}); 
}); 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s