Friday, July 3, 2015

A simple ajax call

Often there is a requirement to populate results on basis of jquery/js + ajax call to populate data on a web page.

A simple use case:
Suppose you have following hierarchy for your flex parent

Main Parent
 - Parent1
   -- SubParent 11
       -- SubSubParent111
       -- SubSubParent112
  -- SubParent 12
       -- SubSubParent121
       -- SubSubParent122
 - Parent 2
   -- SubParent 2
       -- SubSubParent1
.. and so on

and on your webpage you would like show parents and subparents on basis of  user selection on dropdown. For eg: There are 3 dropdowns present for parent, subparent and subsubparent, if first parent is selected as "Parent1", you have to populate 2nd dropdown with "SubParent11" and "SubParent12" and similarly on selection of subparent, have to show corresponding subsubparent dropdown without page load. In such scenario, you can make use of ajax call to populate parents dynamically.

A simple procedure can be:

1. Create one Template or SiteEntry/CSElement and add required params in cache criteria, in our case only one argument would be "parent". If template, make its usage as "Can be called externally via browser"
2. A sample code from calling Template/CSElement can be like following:

//within script tag for localhost can be:
var url = "http://localhost:8080/cs/ContentServer?pagename=GetParent";var selectedParam;
//On parent dropdown selection selectedParam = "&parent="+$(".parent").val();
//On subparent dropdown selection selectedParam = "&parent="+$(".subparent").val();
url = url+selectedParam;
$.ajax({
url: url
}).done(function() {
// Get the output from your Template/CSElement  
// and populate corresponding child parents
});


3. Your called element which you created in 1st step, should output values in either JSON format or XML format or simply text or whatever, its upto you/your HTML.

Note: Further optimization can be done like only one call is sufficient to populate your dropdowns, etc, which depends on your knowledge of JavaScript/Jquery.

Thus, you can call SiteEntry or Template to dynamically inject data from WCS/FatWire on your webpage.

Disclaimer: Any sample code on this blog is not officially recommended, use at your own risk.

2 comments:

  1. i want to create a asset by ajax method .and i try you method ,but get 401 unauthorized error.Does it need to make some configuration for prepare ? really need help .

    ReplyDelete
  2. I should have mentioned this but will update it. The above method will just retrieve already existing data. In order to create asset, you will either use WebCenter Sites REST API or Asset API. There are already some examples provided within guide on creating asset via REST, that should work for you.

    ReplyDelete

A simple code compare functionality

One of the most important aspect of any development cycle is deployment and while deployment, it is very important to note the changes don...