Ajax Helper Module
This new Kentico 10 module provides an interface for creating custom responses to return data from the database in an AJAX request.
Occasionally in JavaScript you will want to access data stored within the Kentico database. Using our JavaScript web part you can insert macros into inline JavaScript, but this isn’t possible for physical files. This module provides a method to create URLs that can be used to easily request data from a SQL or macro data source within your JavaScript files.
You can download the NuGet installation package here: https://devnet.kentico.com/marketplace/modules/ajax-helper. Please note that this module is a proof of concept only, and was not tested with all Kentico versions and in all scenarios.
Using the interface
When you open the Ajax helper module, you will see a listing of all available Ajax handlers and a way to search for specific ones, modify or delete existing ones, and preview the data they return.
The preview button is disabled for Ajax handlers that contain wildcards in the URL path.
When you edit an Ajax handler, you will see three tabs: General, Security, and Preview. In the General tab, you can re-define the data source and URL that you use to access the data.
In the Security tab, you can specify whether the Ajax handler is accessible by anyone with the designated URL, or users with certain roles. In most cases, you should at least specify that only authenticated users can access the data by adding the “Authenticated users” role to list.
The Preview tab allows you to preview the data, similar to the preview button in the listing. However, this tab allows you to specify parameters in circumstances where the Ajax handler contains wildcards, allowing you to preview the data returned by dynamic requests containing variables. This tab displays the raw JSON result as well as a TreeView of the object(s).
The Ajax handler object
Ajax handlers have several common properties:
- AjaxHandlerName: A code name used for identifying Ajax handlers. Follows standard Kentico code naming conventions—it can only contain alphanumeric characters and some special characters.
- AjaxHandlerType: The data returned by the Ajax handler can be retrieved using either SQL queries or macro syntax.
- AjaxHandlerDataSource: The SQL query or macro statement which returns the desired data. The returned object can be a simple string, or even a complex list of InfoObjects such as users. For example, SiteObjects.Documents.TopN(5) is a valid macro statement that will return five TreeNode objects.
- AjaxHandlerUrlPath: A URL path in which the data can be requested from, without leading or trailing slashes. Requests for Ajax handlers are prefixed with /ajaxhelper/ by default, then the URL path. For example, a URL path of GetUsers would be available at http://mysite.com/ajaxhelper/getusers. See the Ajax handlers with wildcards section below for examples of URL paths with variables.
- AjaxHandlerCacheDuration: The time (in minutes) that the response of the Ajax handler will be cached. A value of zero disables caching for the handler.
- AjaxHandlerCacheDependencies: Custom cache dependencies that determine when the cache for this handler will be cleared. You can read more about cache dependencies in our documentation: https://docs.kentico.com/k10/configuring-kentico/optimizing-website-performance/configuring-caching/setting-cache-dependencies. When caching is enabled, an Ajax handler will always use its default cache dependency in the format “ajaxhelper.ajaxhandler|byid|<AjaxHandlerID>”
Ajax handlers are secured according to their related AjaxHandlerRolePermissionInfo object. In the Security tab for an Ajax handler, you can specify whether the handler is accessible to the public, or only users of particular roles. By default, a newly created Ajax handler is only accessible to global administrators.
As mentioned previously, Ajax handlers are accessed from a URL containing the prefix /ajaxhelper/ and their URL path. This prefix can be modified by going to the Settings application, expanding the Integration category, and selecting the Ajax helper node. There, you will find the “Handler identifier” setting which can be set to whatever you’d like. This string should be fairly unique so that requests for pages in your content tree are not mistaken for Ajax requests.
Example- Creating an Ajax handler
In this example we will create an Ajax handler that returns a simple, scalar value when requested: the current user’s first name.
- On the listing page, click the New button in the top-left corner of the page.
- Provide a code name, data source and URL path for the Ajax handler:
- Name: GetUserFirstName
- Data source (Macro): {%CurrentUser.FirstName%}
- URL path: users/current/firstname
- Click Save.
- Switch to the Security tab and select Allow public access. The change is automatically saved.
- Click the Preview tab to ensure your Ajax handler is working properly. The value of Data in the JSON response should be your first name, if set.
Ajax handlers with wildcards
Ajax handler URL paths can contain variables which are passed to the data source, allowing for dynamic requests. In the data source, a variable is referred to by its key surrounded by pound signs.
##keyname##
To specify the location of the value for this variable in the URL, you place a wildcard in the URL path with the same key. A wildcard is indicated by the key name surrounded by braces.
{keyname}
For example, to return a dynamic number of items from a SQL query, you would create an Ajax handler with the following SQL data source and URL path:
- Data source: SELECT TOP ##num## * FROM CMS_User
- URL path: users/top/{num}
The data can then be accessed using URLs containing any valid number at the end:
- http://mysite.com/ajaxhelper/users/top/1
- http://mysite.com/ajaxhelper/users/top/5
Query string parameters
As of v1.1.0, you can pass wildcard values as query string parameters. To create a handler that accepts query string values, create the handler path as usual without wildcards or the query string, and include the variable in your data source as usual. The variable in the data source should have the same name as the expected query string parameter. For example:
- Data source: SELECT * FROM CMS_User WHERE UserName = '##name##' AND UserEnabled = ##enabled##
- URL path: queries/users
This handler will be accessible from a URL such as http://mysite.com/ajaxhelper/queries/users?name=administrator&enabled=1
Handling the AJAX response
The response of an Ajax handler contains properties that will assist you in handling the data. The IsScalar object will always be a Boolean value indicating whether the Data object is simple or complex. When IsScalar is true, you can access the result of the handler directly by referring to the Data object. When it is false, the Data object will be an array, requiring you to access the objects by index—i.e., Data[0], Data[1], etc..
The Success object is a Boolean value, indicating whether the data was properly returned, or if it could not be returned for any reason. Reasons for an error include missing parameters for wildcard paths or unauthorized users, among others. In the event of an error, the IsScalar Boolean value will be true, and the Data object will be a string containing the error message.
Example - Using an Ajax handler in JavaScript
Normally, complex JavaScript would be placed in an external file. However, for the sake of simplicity, we’ll test our new Ajax handler by adding JavaScript to the master page header, even though what our Ajax handler accomplishes is already possible here using macros.
In the Pages module, select your root node in the content tree and click the Master page tab. Enter the following script in the text editor within the <head> tag:
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
var json = JSON.parse(xmlhttp.responseText);
alert("Hello, "+json.Data+"!");
}
};
xmlhttp.open("GET", "~/ajaxhelper/users/current/firstname", true);
xmlhttp.send();
</script>
When you access any page nested within the root node template, an alert will appear with your first name, if set.