AJAX with ATG
ATG droplets and FormHandlers support AJAX call. Below are
the two easy ways to handle AJAX in ATG
Approach 1
- In JS file write a function
$.ajax({
cache : false,
type : "POST",
url : "fragments/shipping.jspf",
data : {
"itemId" : id,
"commerceId" : commerceId
},
success : function(data) {
$('#shippingMethod' + commerceId).html(data);
},
error : function(xhr, ajaxOptions, thrownError) {
}
2. shipping.jsp
Write droplet to render HTML content. which will be available in data under success. Replace the data (HTML content) in the intended DIV.
Apporach 2:
- In Java script write a method to AJAX submit FORM and two callback methods for Success and failure
function callUpdate(){
var options = {
dataType: 'html',
success: callUpdateSuccess,
error: callUpdateError // Error callback
};
$("#formAddToCart").ajaxSubmit(options);
}
function callUpdateSuccess(responseText, statusText, xhr, $form)
{
var responseObject = jQuery.parseJSON(responseText);
alert(responseText);
}
function callUpdateError()
{
alert("Error");
}
2. Once Form get submitted handle method is invoked in form handler. Instead of normal return we will require to return JSON string which needs to be handled under success callback function.
pResponse.setContentType("application/json");
PrintWriter out = pResponse.getWriter();
JSONObject ObjJSON = new JSONObject();
JSONArray arrayJSON = new JSONArray();
JSONArray arrayObj = new JSONArray();
for (CommerceItem item : getOrder().getCommerceItems()) {
JSONObject json = new JSONObject();
json.put("index", item.getId());
json.put("Qty", item.getQty());
arrayObj.add(json);
}
ObjJSON.put("item ", arrayJSON);
out.print(ObjJSON.toString());
out.flush();
out.close();
No comments:
Post a Comment