Suppose we have a two select, one is for selecting subject and another one is populating topic automatically according subject selection: This example I've tried with Ajax and was successful!
**In JSP:**
1. declare this in your jsp
after
First select option for subject selection
inlineField="true" onChange=''>
int totalsubject = SubjectLocalServiceUtil
.getSubjectsCount();
List subjectList = SubjectLocalServiceUtil
.getSubjects(0, totalsubject);
for (Subject subject : subjectList) {
%>
}
%>
second select option for populating topics automatically according subject selection above.
write a javascript function which will be executed onChange of the value of subject as shown:
Liferay.provide(
window,
'fetchTopics',
function() {
var A = AUI();
var fetchTopicsURL = '';
// selecting the sourceSelect drop-down to get the current value
var sourceElement = A.one("#subject");
// selecting the targetSelect drop-down to populate values
var targetElement = A.one("#topic");
A.io.request (
// the resource URL to fetch words
fetchTopicsURL, {
data: {
// request parameters to be sent to the Server
subject: sourceElement.val()
},
dataType: 'json',
on: {
failure: function() {
// if there was some error at the server
alert("Ajax failed! There was some error at the server");
},
success: function(event, id, obj) {
// JSON Data recieved from Server
var topicsArray = this.get('responseData');
// crude javascript magic to populate the drop-down
//clear the content of select
targetElement.html("");
for (var j=0; j < topicsArray.length; j++) {
targetElement.append("" + topicsArray[j] + "");
}
}
}
}
);
},
['aui-io']
);
That's all your jsp coding! :)
Next part is to write a method your portlet class as shown below:
@Override
public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
String subject = ParamUtil.getString(resourceRequest, "subject");
// build the JsonArray to be sent back
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
//put some topics
if(subject.equals("Maths")){
jsonArray.put("Math1");
jsonArray.put("Math2");
jsonArray.put("Math3");
}
if(subject.equals("Science")){
jsonArray.put("science1");
jsonArray.put("science2");
jsonArray.put("science3");
}
// set the content Type
resourceResponse.setContentType("text/javascript");
// using printWrite to write to the response
PrintWriter writer = resourceResponse.getWriter();
writer.write(jsonArray.toString());
}
That's all your coding.. :)