Wednesday, 24 July 2013

combo-box(Drop down) Change event populate or fetch value from table using ajax in liferay

Hi Friends ,

Today i want to share small ajax portlet example with you . As every post i explain step by step..

I have one combo box & when user change value so according that onchange event i fetch value from db using ajax.


As In above image when user select birthday category then in fetch keyword from db table & append multi select .

Now time for code :

First In Jsp File write below code:

<portlet:resourceURL var="fetchValues" id="fetchcombo"></portlet:resourceURL>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>

<script>
$(document).ready(function() {
       $("#category").change(function() {
var keyId=$("#category").val();
document.getElementById("Features").innerHTML="";

                       var url = "<%=fetchValues%>";
           $.post(url, {keyId : keyId}, function(data)  {
               


for(var z=0; z<data.dataarray.length;z++){

dataarray = data.dataarray[z].split(":");
                        $("#Features").append("<option value="+dataarray[0]+">'"+dataarray[1]+"'</option>");
}
});
       });
});
</script>
        <select id="category" name="category">
        <option value="null" selected="selected">--select--</option>
               <option value="123">BirthDay</option>
      </select>

            <select id="Features" name="Features" size="20" multiple="multiple" style="width: 200px;">
           
            </select>
Now in  java class You have to implement serveResource method for handle ajax call.


public void serveResource(ResourceRequest resourceRequest,
ResourceResponse resourceResponse) throws IOException,
PortletException {
long keyId = ParamUtil.getLong(resourceRequest, "keyId");
if (action.equalsIgnoreCase("first")) {
System.out.println("call serveResource Method");
String keyname = null;
JSONArray dataarray = JSONFactoryUtil.getJSONFactory()
.createJSONArray();
JSONObject json1 = JSONFactoryUtil.createJSONObject();
long keywordid = 0l;
try {
List<Keyword_Master> l = Keyword_MasterLocalServiceUtil
.getByCatId(keyId);        // here i used finder method to get  value
for (int i = 0; i < l.size(); i++) {
keyname = l.get(i).getKeywordName();
keywordid = l.get(i).getKeyId();
dataarray.put(keywordid + ":" + keyname);

}
json1.put("dataarray", dataarray);

} catch (SystemException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
resourceResponse.setContentType("application/json");
resourceResponse.setCharacterEncoding("UTF-8");
resourceResponse.getWriter().write(json1.toString());
}

}
Any query raise then comment or send email on chiragmsc007it@gmail.com

No comments:

Post a Comment