Tuesday, 11 December 2012

AJAX CALL IN LIFERAY

for drop down country->states->cities
using
step 1)gson.jar
step 2)create url 
<portlet:resourceURL var="ajaxCallResourceURL" />

step 3) script

 function dropdownStates(x,id) {
   AUI().use('aui-io-request',
   function callServer(A)
   {
   
    var stateid=id.substr(0,9);
   
    var dropdownId='#'+stateid+'states';
    var dropdownId1='#'+stateid+'cities';
       var countryValue  = x;
       var countryParameter="country";
       
    A.io.request("<%=ajaxCallResourceURL%>", {
        method: 'POST',
dataType: 'json',
data : {
country : countryValue,
callFor : countryParameter
},
           on : {
            success: function() {
            var states = this.get('responseData');
           
            var selectObject = $(dropdownId);
            var selectObject1 = $(dropdownId1);
            $('>option', selectObject).remove();
            $('>option', selectObject1).remove();
            $.each(states, function(key, value) {
            selectObject.append($('<option/>').val(key).text(value));
                         });
            },

failure: function()
{
alert("Failed to fetch the state for this country. Please try agian.");
}
           }
         
       } );
     
   });
}

function dropdownCities(x,id) {
   AUI().use('aui-io-request',
   function callServer(A)
   {
   
    var stateid=id.substr(0,9);
    var dropdownId='#'+stateid+'cities';
    var stateValue  = x;
       var stateParameter="state";
       
    A.io.request("<%=ajaxCallResourceURL%>", {
        method: 'POST',
dataType: 'json',
data : {
state : stateValue,
callFor:stateParameter
},
           on : {
            success: function() {
            var cities = this.get('responseData');
           
            var selectObject = $(dropdownId);
            $('>option', selectObject).remove();
            $.each(cities, function(key, value) {
            selectObject.append($('<option/>').val(key).text(value));
                         });
            },

failure: function()
{
alert("Failed to fetch the Cities for this state. Please try agian.");
}
           }
         
       } );
     
   });
}

step 4) in which filed,ajax call invoke


<div style="width: 100%;margin-top: 10px;height: 18px;font-size: 12px;font-weight: bold;" >
    <div style="float: left;width: 30%"><font style="color: red;size: 12px">* &nbsp;</font>Country</div>
    <div style="float: left;width: 50%">
    <select style="width: 97%;" onchange="dropdownStates(this.value,this.id)" id="corresponCountry" name="Country" label="">
    <c:forEach items="${countries}" var="countries">
    <option value="<c:out value='${countries.countryCode}'/>">
    <c:out value="${countries.countryName}"/>
    </option>    
    </c:forEach>
    </select>
</div>
     
    </div>
    <div style="width: 100%;margin-top: 10px;height: 18px;font-size: 12px;font-weight: bold;" >
    <div style="float: left;width: 30%"><font style="color: red;size: 12px">* &nbsp;</font>State</div>
    <div style="float: left;width: 50%" >
    <select style="width: 97%;" onchange="dropdownCities(this.value,this.id)"  id="corresponstates" name="states" label="">    
    </select>
    </div>
     
    </div>
    <div style="width: 100%;margin-top: 10px;height: 18px;font-size: 12px;font-weight: bold;" >
    <div style="float: left;width: 30%"><font style="color: red;size: 12px">* &nbsp;</font>Town</div>
    <div style="float: left;width: 50%">
    <select style="width: 97%;"  id="corresponcities" name="cities" label="">
   
    </select>
    </div>
   
    </div>


step 4) In controller class

public void serveResource(ResourceRequest request, ResourceResponse response)
throws IOException, PortletException {
String callFor = request.getParameter("callFor");
----
----
----

if ("country".equalsIgnoreCase(callFor)) {
int country = Integer.parseInt(request.getParameter("country"));
String values = new String();
List<State> states = commonService.findStatesForCountry(country);
Gson gson = new Gson();
values = gson
.toJson(ControllerHelper.convertStateListToMap(states));
response.getWriter().write(values);
}

else if ("state".equalsIgnoreCase(callFor)) {
String values = new String();
int state = Integer.parseInt(request.getParameter("state"));

List<City> cities = commonService.findCitiesForState(state);
Gson gson = new Gson();
values = gson.toJson(ControllerHelper.convertCityListToMap(cities));
response.getWriter().write(values);
}
}



2 comments:

  1. Hi Arvind , This is really a knowledgeable article and thanks for sharing this . I want to add one more thing as a suggestion if you are having more than one ajax call then try to create a generic method rather than creating more methods ....
    For Example : I have modularized the code in this way :
    function ajaxPush(targetDiv, requestURL, postData, syncMode) {
    A.use('aui-io-request', function(A) {
    A.io.request(requestURL, {
    method: 'POST',
    dataType: 'html',
    data: {
    postKey: postData
    },
    sync: syncMode,
    on: {
    start: ajaxPushStartEventManager(targetDiv),
    success: function() {
    ajaxPushSuccessEventManager(targetDiv, this.get('responseData'));
    },
    failure: function() {
    ajaxPushFailureEventManager(targetDiv, this.get('responseData'), requestURL);
    }
    }
    });
    });
    }
    function ajaxPushStartEventManager(targetDiv) {
    // Do somethings
    }

    function ajaxPushSuccessEventManager(targetDiv, responseTxt) {
    if (targetDiv == tableDiv) {
    A.one(targetDiv).html(responseTxt);
    }
    }

    function ajaxPushFailureEventManager(targetDiv, responseTxt, requestURL) {
    if (targetDiv == tableDiv) {
    // Do something
    }
    }

    ReplyDelete
    Replies
    1. Thanx Ratan i will use your valuable advice...

      Delete