Thursday, 4 July 2013

Struts + Ajax + JSON

It wasn't my first experiment with Struts or Ajax or jsp! Despite this fact, I ran into problems and had to spend time to fix it. So let me share what dawned to me (I'm specifically avoiding term 'what I learnt'...since I already knew it).

My home.action had jsp with div in it which would open as a popup with a link click.

<s:textfield id="fullName" value="%{datamodel.fullName}" placeholder="Full Name"/>
In brief, on click of the link, it was supposed to show the div with values populated, fetched from db.

Action class with a method to serve my need was already in place to fetch data and populate in bean. However the action was returning another jsp. Using the same method in Action class, making an additional entry which returned result type as json, did the job.

<action name="homePage" class="HomePageAction" method="loadUserData">
     <result type="json"></result>
</action>

I wrote a function to send ajax request (to be called with link click):

function loadData(index){

var userName = $("#userName").val();

$.ajax({

type: "GET",

url : '/site/loadUserData.action?userName ='+userName,

success: function(data){

     showProfile();

   }

 });

}

I was getting 'data' in success part of ajax request. Happy! I was expecting the bean values to be displayed on the pop up since bean is populated and popup opens after that. But I continued to see blank fields. Disheartened!

The reason behind it was straightforward(though it didn't trigger me while I was working on it!): jsp got rendered when home.action was called. That time bean was not having values. Jsp displayed/resolved the values it had at that time. Now when I click link, send ajax request, get json response, how would jsp be aware of that!

Setting the values of fields on success of ajax(), before opening the pop up call was the way out:

$.ajax({

type: "GET",

url : '/site/loadUserData.action?userName ='+userName,

success: function(data){

showProfile(data.profileVO);

  }

 });

function showProfile(profileVO){

  $("#fullName").val(profileVO.fullName);

}


Happy ajaxing & struting(strutting ;) ).


No comments:

Post a Comment