Gregory's Blog

Introducing the Kendo Grid


The Kendo UI Grid is one of the most functional and elegant HTML5-based grid systems around. The Kendo UI Grid is used to easily allow users to visualize and interact with extremely large datasets- I have personally used Kendo Grids to convey over 60 million (60,00,000) records at a time using virtualization. The grids support paging, sorting, filtering, frozen columns, grouping, pivoting, etc, and allow for the editing of records. Grid data can also be exported to excel or pdf.

The grids are themeable and fully integrated with the other Kendo UI widgets and other Kendo UI widgets, such as Kendo dropdowns, can be embedded into a cell. The Kendo grids can be used natively with Angular, React, Vue and jQuery. Additionally, there are PHP and .Net wrappers, and Kendo UI can be easily used with ColdFusion as well. In this article we will show you how to use the grids with ColdFusion, however, like the rest of our articles, the client logic is written in JavaScript and jQuery and is server agnostic- you should be able to follow along.



Kendo Grid Demonstration

Please click on the button below to see the Kendo UI Grid that uses this code.


When Should You Use a Kendo UI Grid?

I use Kendo UI Grids every time I would typically use an HTML table to convey tabular data. The Kendo UI grids are interactive and offer a lot of improvements over a traditional HTML table, such as adding the ability to sort and group the data and will create a uniform look and feel when using a Kendo Theme. 


Kendo UI Grid Initializing and Binding Options

Kendo UI grids can be initialized using a simple HTML table or from a remote data service.

If the grids are initialized from a data service, the data can be bound to:

  1. Local JavaScript Data
  2. Remote Server Endpoint
  3. Kinvey Backend Services
  4. GraphQL Service
  5. SignalR
  6. WebSockets

In this series of articles, we will focus on binding the grids both locally and to a ColdFusion Service Endpoint.


CfBlogs Database Background

In the examples below, we will use ColdFusion to make a query to the cfblogs.org RSS blog aggregator database (formerly cfbloggers). The Cfblogs.org database collects data every 15 minutes from over 147 different ColdFusion blog sites and is updated whenever a new blog post is made and generates a tweet that summarizes the new blog post on Twitter.


Initializing a Grid from a Table

In the demonstration below, we will create a Kendo Grid from a static table showing the top ColdFusion-related blogs according to the number of posts made in the last calendar year.

In this example, we are querying the CfBlogs MySql database for active blogs, counting the number of blog posts in the last year, and getting the date of the last post. We are then looping through the query to create the data within the table cells. This code should be familiar to the ColdFusion developer.


SELECT	
		COUNT(e.posted) as count,
		MAX(date_format(e.posted, '%m/%d/%Y %r')) as maxDate,
		b.name as blog, 
		e.categories, 
		b.description as blogdescription, 
		b.url as blogurl,
		b.blogsoftware
	FROM	entries e, blogs b
	WHERE	e.blogidfk = b.id
	AND b.active = 1
	AND e.title is not null
	AND  e.posted > now() - INTERVAL 12 month
	GROUP BY blog
	ORDER BY count DESC
</cfquery>

<table id="grid">
	<colgroup>
		<col style="width:10%" />
		<col style="width:25%" />
		<col style="width:50%" />
		<col style="width:15%" />
	</colgroup>
	<thead>
		<tr>
			<th data-field="count"># Posts</th>
			<th data-field="blog">Blog</th>
			<th data-field="blogdescription">Description</th>
			<th data-field="maxDate">Last Post</th>
		</tr>
	</thead>
	<tbody>
	<cfoutput query="Data">
		<tr>
			<td>#count#</td>
			<td><a href="#blogurl#" target="new">#blog#</a></td>
			<td>#blogdescription#</td>
			<td>#maxDate#</td>
		</tr>
	</cfoutput>
	</tbody>
</table>

After generating the table, we simply initialize the Kendo UI Grid using a few lines of Javascript.

We are specifying the id of the table, grid, to initialize the grid. There are a few additional optional arguments that we will use to make this grid sortable.

The sortable argument makes the Kendo UI grid, well you guessed it- sortable, and the columnMenu argument places a menu at the top of the grid. The columMenu argument takes multiple additional arguments, and here we want to set filterable to false as we are binding the data to an HTML table.

These methods will be covered in more detail in future blog posts.


<script>
	$(document).ready(function() {
		$("#grid").kendoGrid({
		sortable: true,
		columnMenu: {
			filterable: false
		}
		});
	});
</script>


Initializing a Kendo UI Grid Using a ColdFusion Remote Server Endpoint


Server Side Code Using ColdFusion

The following function is in the Demo.cfc ColdFusion Component. You don't need to use a ColdFusion component as the service endpoint, you can use any ColdFusion template, however, it is useful to use a component with multiple methods for a variety of reasons. Namely, ColdFusion components use an object-oriented approach, they are generally faster than a UDF, and they are generally more secure and extensible.

This function is no different than the server-side functions that we used for the Kendo dropdowns in previous articles. We are simply querying the database and transforming the ColdFusion query object into JSON using our CfJson method and returning the JSON string. You should note that we are also using returnFormat="json"  in the function declaration.


<cffunction name="getLastYearTopBlogsForGrid" access="remote" returnformat="json" output="false" 
		hint="Returns the most active ColdFusion blogs by most recent date for the last calendar year">
	<!--- There are no arguments for this function. --->
	<cfsetting enablecfoutputonly="true" />

	<cfset dsn = "cfbloggers">

	<cfquery name="Data" datasource="#dsn#">
		SELECT	
			COUNT(e.posted) as count,
			MAX(date_format(e.posted, '%m/%d/%Y %r')) as maxDate,
			b.name as blog, 
			e.categories, 
			b.description as blogdescription, 
			b.url as blogurl,
			b.blogsoftware
		FROM	entries e, blogs b
		WHERE	e.blogidfk = b.id
		AND b.active = 1
		AND e.title is not null
		AND  e.posted > now() - INTERVAL 12 month
		GROUP BY blog
		ORDER BY count DESC
	</cfquery>

	<!--- Using my jsonArray.cfc --->
	<!--- Convert the query object into JSON using the convertCfQuery2JsonStruct method --->
	<cfinvoke component="#jsonArray#" method="convertCfQuery2JsonStruct" returnvariable="jsonString">
		<cfinvokeargument name="queryObj" value="#Data#">
		<cfinvokeargument name="includeTotal" value="false">	
	</cfinvoke>

	<cfreturn jsonString>
</cffunction>

The JSON String Returned by the ColdFusion Endpoint

The ColdFusion server endpoint returns the following JSON. Note: I formatted the JSON and have only included the first 5 records for brevity.

[{
	"maxDate": "12/31/2021 01:46:00 AM",
	"total": 30,
	"blogsoftware": "http://wordpress.org/?v=2.9.2",
	"count": 206,
	"blogurl": "https://www.bennadel.com
",
	"id": 134,
	"blogdescription": "Ben Nadel's web development blog on ColdFusion, jQuery, HTML5, AJAX, SQL, and all aspects of web application development.",
	"blog": "Ben Nadel",
	"categories": "ColdFusion"
}, {
	"maxDate": "11/08/2021 10:51:00 PM",
	"total": 30,
	"blogsoftware": "FeedGenerator",
	"count": 124,
	"blogurl": "https://www.intothebox.org
",
	"id": 144,
	"blogdescription": "ContentBox",
	"blog": "ContentBox",
	"categories": "News, Schedule, Speakers"
}, {
	"maxDate": "12/17/2021 11:29:11 AM",
	"total": 30,
	"blogsoftware": "https://wordpress.org/?v=5.6.1",
	"count": 111,
	"blogurl": "https://coldfusion.adobe.com
",
	"id": 104,
	"blogdescription": "Connect with community",
	"blog": "ColdFusion",
	"categories": "Announcements,Blog,Online ColdFusion Meetup,announcements,blog,ColdFusion,online coldfusion meetup"
}, {
	"maxDate": "11/13/2021 06:00:00 PM",
	"total": 30,
	"blogsoftware": "Eleventy",
	"count": 77,
	"blogurl": "https://www.raymondcamden.com
",
	"id": 152,
	"blogdescription": "DevRel at large, Star Wars nerd, Web/Serverless hacker, lover of good beer and good books. Oh, and cats.",
	"blog": "Raymond Camden",
	"categories": "eleventy,static sites"
}, {
	"maxDate": "10/20/2022 04:45:00 PM",
	"total": 30,
	"blogsoftware": "Galaxie Blog",
	"count": 74,
	"blogurl": "https://www.gregoryalexander.com/blog/",
	"id": 1,
	"blogdescription": "A technical blog powered by Galaxie Blog - the most beautiful and functional open source ColdFusion/Kendo UI based blog in the world.",
	"blog": "Gregory's Blog",
	"categories": "Galaxie Blog"
}]

Inspect the JSON Yourself Using the Browsers Inspector

For debugging purposes, you often will want to inspect the JSON yourself using the browser's developer tools

All of the major browsers have some type of developer console to inspect the web page elements and browser traffic. If you're using Chrome, launch the DevTools console by pressing the F12 button, or if you're on a Mac, press the function and F12 key at the same time. 

Once the DevTools inspector is open, click on the network tab, and refresh the Kendo window and you should see a link to the Demo.cfc?method=topBlogsByPostsForCalendarYear in the list to the right. Click on it to see the JSON string returned from the server. For more information on the inspector, please refer to your browser's documentation.



The Kendo DataSource

The following Kendo DataSource invokes the topBlogsByPostsForCalendarYear function in the Demo.cfc ColdFusion component that we covered above. There is nothing different than the data source logic that we used in previous articles, however, in future Kendo Grid-related articles, we will identify the datatype inside the data source for advanced grid handling.

var topBlogsByPostsDs = new kendo.data.DataSource({
	// Determines which method and cfc to get and set data.
	transport: {
		read: {
			url: "<cfoutput>#application.baseUrl#</cfoutput>/demo/Demo.cfc?method=topBlogsByPostsForCalendarYear", // the cfc component which processes the query and returns a json string.
			dataType: "json", // Use json if the template is on the current server. If not, use jsonp for cross domain reads.
			method: "post" // Note: when the method is set to "get", the query will be cached by default. This is not ideal.
		}//read:
	},//transport:
	cache: false
});//topBlogsByPostsDs = new kendo.data.DataSource

Initializing the Kendo UI Grid

The script to initialize the grid inserts the grid widget into the grid div in the client-side code.

We are using the topBlogsByPostsDs data source and setting the basic grid options to allow sorting and allowing the user to search the grid for data using filterable: true. We will cover the column menu arguments in later articles.

Arguments in the columns array are optional, you can omit them, however, the grid will render all of the columns with equal widths and the column title will be the name of the database column which is not ideal.

The columns array should always be used with the Kendo UI grid in order to specify the column title, whether you want the column to have search filters, and to set the column widths. 

Here we are applying the column database name to the field, setting the title of the column, specifying whether the column filter menus are available, and set the column widths. The width argument can be a numeric value if you want to set a pixel width, or as a string, if you want to use percents.

var topBlogsByPosts = $("#grid").kendoGrid({
	dataSource: topBlogsByPostsDs,
	sortable: true,
    columnMenu: {
        filterable: false
    },
    // Column properties
    columns: [{
        field:"count",
        title: "# Posts",
        filterable: true,
        width:"15%"
    }, {
        field:"blog",
        title: "Blog",
        filterable: true,
        width:"20%"
    }, {
        field:"blogdescription",
        title: "Description",
        filterable: true,
        width:"50%"
    }, {
        field:"blogurl",
        title: "URL",
        filterable: true,
        width:"20%"
    }]// columns:
});// var topBlogsByPosts = $("#grid").kendoGrid

Client Side Code

The client-side code should be self-explanatory- the only thing of note here is that we are placing a div with the id of grid that is used to contain the Kendo grid.

<h2>Most active ColdFusion blogs in the last year</h2>
<p>Based upon the number of posts made within the last year according to <a href="www.cfblogs.org">CfBlogs.org</a></p>

<!--- Empty iv container for the grid. --->
<div id="grid"></div>

We will be covering more advanced Kendo UI Grid examples in future articles.

Thanks for reading!

Further Reading


This entry was posted on October 31, 2022 at 10:10 PM and has received 210 views.

Dynamically Populating Kendo MultiSelects


As we previously mentioned, the Kendo MultiSelect widget offers significant enhancements to a traditional dropdown menu and can be used to replace a long list of checkboxes. In this article, we will take a deep dive into the Kendo MultiSelect, show how it can be prepopulated with existing values, and how to dynamically populate it using cascading dropdowns.

Like the rest of the posts in this series, we will be using ColdFusion on the server side, however, it should be easily understood if you use a different server-side language, and you should be able to follow along.



Visual Demonstration of Kendo's MultiSelect vs HTML MultiSelect

A picture is worth a thousand words. I am going to contrast the Kendo MultiSelect against traditional HTML checkboxes to visually convey the benefits of using the Kendo MultiSelect.

In the following interfaces, we are prepopulating the form with the US states on the Pacific seaboard selected.


Kendo MultiSelect

As you can see here, with the Kendo MultiSelect the selected values are front and center allowing the user to quickly see what is selected without forcing them to scroll down a long list of items. The Kendo MultiSelect also has search functionality to allow the user to quickly select additional values. The Kendo MultiSelect is also much more elegant and it takes up less space on the screen.

The Kendo MultiSelect's ability to put information front and center makes it a perfect tool to conceptualize related groups of information, however, in order to convey this we need to be able to dynamically populate this list.


Traditional HTML Multi-Select

The traditional multi-select requires you to scroll way down to see Oregon and Washington that are selected, and you better make sure not to accidentally click on one of the items while scrolling or the selection will be gone!


Dynamically Removing the Selected Kendo MultiSelect Options

To remove all of the selected values in the Kendo MultiSelect, simply pass an empty array to the MultiSelect value method like so:

$("#stateDropdown").kendoMultiSelect({
	placeholder: "Select...",
	autoBind: false,
	dataTextField: "name",
	dataValueField: "id",
	filter: "contains",
	dataSource: stateDs,
	value: []
}).data("kendoMultiSelect");

Populating a Kendo MultiSelect With Initial Values

Use the MultiSelect value method to populate the values of a Kendo MultiSelect.

You can either use an array with comma-separated values or an array of structures for the value.  This value must have the same value and datatype as the data element that is used to populate the dataValueField. If the value and the data type do not match a data element used to populate the dataValueField, the value will be ignored. We will illustrate this below.

All of these examples are valid:

// Displays United States
value: [{ name: "United States", id: 233 }] // Note: the name will be ignored. 
value: [{ id: 233}]
value: [233]
// Displays United States, United States Minor Outlining Areas
value: [233,234]
value: [{id:233},{id:234}]

However, these examples do not work. See comments in code:

[{ name: "United States" }] // United States does not match a data element in the dataValueField and will be ignored
"233,234,235"// Missing array (the square brackets)

Dynamically Populating a Kendo MultiSelect


Overview

To dynamically populate a Kendo MultiSelect, we need to inspect data using either AJAX or using the Kendo DataSource and prepare the data for the MultiSelect value method.

If you're using jQuery AJAX, and the data from the server is already a comma-separated string or an array of structures, you may be able to dump the data into the Kendo MultiSelects value method. Otherwise, you will have to prepare the string or array by looping through the data.

If you're inspecting data from a Kendo Datasource, we will use a similar approach that we would use to interrogate the data using jQuery Ajax- we will loop through the data triggered by a parent Kendo widget and populate the values array using the JavaScript push method and use the new array in the Kendo MultiSelect value method. 

In this article, we will focus on interrogating data from the Kendo DataSource.


Potential Use Cases

Unlike the traditional HTML MultiSelect, a Kendo MultiSelect can be prepopulated with values to allow the user to easily visualize and interact with related groups of data. I often populate the MultiSelect widget to allow the users to conceptualize related data with a predefined starting point.  

There are many other reasons to dynamically populate the MultiSelect. For example, we can clean up the selected values in a MultiSelect if the child values don't relate to other parent data. For example, in our previous Cascading MultiSelect article, we dynamically removed states from a child MultiSelect when the state's country was removed in the parent country MultiSelect menu. 


MultiSelect Dynamic Population Demonstration

The following example allows the user to select a world region that they are interested in exploring. Once the user selects a world region, the region states will be dynamically populated in the child state multi-select.

We will go over the details of this code later in this article.

Countries by subregion

Extracting Data from a Kendo DataSource

To extract the data from a Kendo DataSource, we need to use Kendo's data method on the Kendo DataSource. Unfortunately, we can't use this data to directly populate the MultiSelect's value method as the JSON extracted from the Kendo DataSource has been transformed into a specialized Kendo Observable Array JavaScript object. Instead, we need to loop through the data and create a string of values separated by commas using the JavaScript push method.

The populateCountry function below performs all of the necessary steps to extract the data from the countryDs data source and populates the country MultiSelect with values. This function is invoked using the change method on the parent subregion dropdown when the user selects a country. The full code is provided at the end of this article.

This function will use the data method on the countryDs Kendo DataSource that was consumed via the change function invoked when the user selects a subregion. Here, we don't need to use the Kendo fetch or read method as the data source already consumed the service endpoint when a region was selected. We will cover the fetch and read methods in future articles, but they don't apply here.

After using the Kendo DataSource's data method, we will create an empty countryIdList array to hold the list of values that we will later use in the MultiSelect's value method and loop through the data, which is a specialized JavaScript array.

Our loop will be a simple JavaScript for loop, and we will continue to loop through the records until there are no more records in the Kendo Observable array.

Inside this loop, we will extract the items that we need to populate the Kendo MultiSelect. In this example, we are getting the id, which is the primary key of the country table. Once the id has been extracted, we will use the JavaScript push method to push the value into the new countryIdList array that we just created.

After the loop has been completed and all of the ids have been saved to our new array, we will use this countryIdList to populate the MultiSelect using the widgets value method.

Here is the function:


The populateCountry function

// Populate the selected MultiSelect values from the datasource	
function populateCountries(e){
	// Get the data from the datasource
	var data = countryDs.data();
	// Create an array that we will use to populate the dropdown
	var countryIdList = [];
	// Loop through the data to create an array to send to the multi-select
	for (var i = 0; i < data.length; i++) {
		// Get the countryId
		var countryId = data[i].id;
		// Populate our new array with the value surrounded by qoutes
		countryIdList.push(countryId);
	}//..for (var i = 0; i < capabilityDsData.length; i++) {
	// At the end of the loop, opulate the multiSelect with the array that we just built
	countryDropdown.value(countryIdList);
}//..function...

This entry was posted on October 21, 2022 at 12:45 AM and has received 150 views.

Cascading Kendo MultiSelect Dropdowns


In this example, we will demonstrate how to create cascading menus' with Kendo MultiSelects. We have covered cascading menus with the dropdown lists, but there are fundamental differences.

Telerik has an example of how to create cascading dropdowns with MultiSelects, however, in my opinion, it is too complex and will suggest a simpler straightforward event-based approach. We will also briefly cover how to inspect the data coming from the parent dropdown data source and use the JavaScript push method to deselect MultiSelect values chosen by the user as well as using the Kendo DataSource to group city data in the menu.

In this example, I will try my best to replicate the UI of James Moberg's 'North America Search Demo' found at https://www.sunstarmedia.com/demo/countrystate/. James is a frequent contributor to the ColdFusion community and his elegant demo is used in production environments. Jame's demo uses a different library, Select2 UI, but it uses the same concepts that we want to show here.

Like the rest of the posts in this series, we will be using ColdFusion on the server side, however, it should be easily understood if you use a different server-side language, and you should be able to follow along.



Cascading MultiSelects Demonstration

 

Cascading MultiSelects Approach

We have already introduced this approach in our previous Cascading Country, State and City Kendo UI Dropdowns article and will briefly cover the major details.

Gregory's Approach to handle cascading dropdowns:

  1. Initialize the dropdowns as you normally would- but add an onChange method.
  2. Use the drop-down widgets onChange method to:
    1. Capture and store the user's selection into a hidden form field.
    2. Refresh any dependent dropdowns using the widgets refresh method.
  3. The data sources belonging to the dependent dropdowns will pass the necessary values in the hidden form fields to the remote end-point.
  4. If necessary, use the DataSource's onChange method to:
    1.  dynamically populate the values of a dependent MultiSelect
    2. or validate the data and perform any additional logic.

Differences in this approach when using the MultiSelect

  • For the most part, the cascading MultiSelect dropdowns are nearly identical to the cascading dropDownLists that we have already covered.
  • For the dependent multi-select dropdown, we are using different server-side logic in order to query the database allowing multiple choices for cities and countries. 
  • The major differences on the client side are that we are using multi-selects and passing comma-separated values to the server, and we are not disabling the multi-selects when there is a change in the state dropdown.
  • We are not using the Kendo DropDownList's select argument to set the default value of the Kendo MultiSelect when changes are made to the parent dropdowns. Instead, when a state is deselected; we need to dynamically recreate the values in the MultiSelect.

First Country Dropdown

The first dropdown is a Kendo DropDownList widget; I could have made it a multi-select, but the city list is already quite long even when a unique state is selected. I did not want to have a scenario where cities are shown for multiple states and multiple countries. This would negatively impact the performance of the UI and potentially crash the browser.

This dropdown is identical to the state dropdown in our Cascading Country, State, and City Kendo UI Dropdowns article. This dropdown list contains the flags of each country, if you are interested in how to accomplish this please see Adding the Country Flag to the DropDownList

Since we have already covered this dropdown, I will not share the code or elaborate on the details but will include the links to the original article below:

  1. Create the first dropdown
  2. Create The Country Dropdown Kendo Datasource
  3. Adding the Country Flag to the DropDownList
  4. Initialize the Country DropDownList
  5. The Country DropDownList onChange Event

Second State MultiSelect Dropdown

The state multi-select dropdown is dependent on the country dropdown and contains all of the states for the selected country and is a required field.

The user must select either one or more states. The state onChange event is used to fire another function to populate the cities into the next multi-select dropdown. The state multi-select dropdown is quite similar to the state dropdown-list, but has a few changes that I will note.


Server-Side Logic with ColdFusion

We are going to use the same method from the World.cfc that we discussed in our Using ColdFusion to Populate Kendo UI Widgets article. In a nutshell, this method queries the World, Countries City database and converts the ColdFusion query into a JSON string using our CfJson ColdFusion component. In this example, we are passing in the countryId from the country dropdown. We don't need to pass multiple values as the parent country dropdown is a Kendo DropDownList and not a MultiSelect.

Here is the server-side code:

<cffunction name="getStates" access="remote" returnformat="json" output="true"
		hint="Gets the world states by a variety of optional arguments">
	<cfargument name="countryId" type="string" required="false" default="" />

	<cfquery name="Data" datasource="cityDb">
		SELECT id, name, latitude, longitude FROM states
		WHERE 0=0
	<cfif len(arguments.countryId)>
		AND country_id = <cfqueryparam value="#arguments.countryId#" cfsqltype="integer">
	</cfif>
		ORDER BY name
	</cfquery>

	<!--- Convert the query object into JSON using the convertCfQuery2JsonStruct method --->
	<cfinvoke component="#application.cfJsonComponentPath#" method="convertCfQuery2JsonStruct" returnvariable="jsonString">
		<cfinvokeargument name="queryObj" value="#Data#">
		<cfinvokeargument name="includeTotal" value="false">	
	</cfinvoke>

	<!--- Return it. --->
	<cfreturn jsonString>

</cffunction>

The State Kendo DataSource

In this example, even though we are using a MultiSelect here instead of a DropDownList, the Kendo data source of the state dropdown is identical to the DropDownList state data source in our previous article. The only difference here is that in this example, the data-sources change method is used on rare occasions to enable and populate the cities dropdown when there is no state.

// ----------- State Datasource. -----------

// First state dropdown.
var stateDs = new kendo.data.DataSource({
	transport: {
		read: {
			cache: false,
			// The function allows the url to become dynamic to append additional arguements.
			url: function() { return "<cfoutput>#application.baseUrl#</cfoutput>/demo/WorldCountries.cfc?method=getStates&countryId=" + $('#selectedCountry').val(); },
			dataType: "json",
			contentType: "application/json; charset=utf-8", // Note: when posting json via the request body to a coldfusion page, we must use this content type or we will get a 'IllegalArgumentException' on the ColdFusion processing page.
			type: "POST"
		}
	},
	// Function to enable the city dropdown when a state does not exist for a selected country. This will only fire when there is no data in the Kendo datasource and will enable the city dropdown in order for the user to still be able to pick a city. This is fired everytime there is a change to the state datasource
	change: function() {
		// Get the datasource length
		var data = this.data();
		// Set a var for the city dropdown list.
		var cityDropdown = $("#cityDropdown").data("kendoMultiSelect");
		// If there are no states for this country...
		if (!data.length){
			// Now enable the city dropdown list.
			cityDropdown.enable();
			// Refresh the city dropdown
			cityDropdown.dataSource.read();
			// Note: we are not disabling the city MultiSelect in an else block if there is no data. Doing so would disable the city dropdown if you have made a new city selection.
		}//if (! data.length){..

		// Get the Kendo button at the end of the interface
		var cityButton = $("#cityButton").data("kendoButton");
		// Disable the the button
		cityButton.enable(true);

	}//change: function() {..
});//var stateDs...

// Note: in the cascading dropdown example, we are using the select event for the state dropdown to set the option to the default 'Select...' placeholder (stateDropdown.select(0)). However, this is not necessary here, and the select method does not exist for the multiSelect

Initializing the State MultiSelect

This is nearly identical to the state drop-down list example in our previous article. There are a few differences- we are substituting the string kendoMultiSelect for kendoDropdownList, using placeHolder instead of optionLabel for the hint. We are also calling functions via two MultiSelect events- the change event, which we have already covered, and a new deselect event that is specific to the Kendo MultiSelect.

Introducing Kendo MultiSelect Deselect Event

As we previously discussed in our prior article, every widget supports a certain set of events. Often, an event may be unique to a particular widget, such as the deselect event here with the Kendo MultiSelect.

All of the widgets supported events are documented on the Kendo UI site- search for the widget documentation and click on the API button.

Here, we need to use the deselect event to determine if any cities should be removed if the user deselects a given state. This event is fired every time a user removes one of the multi-select elements that they have previously chosen. We will use this event to remove any chosen cities when the parent state is deselected by the user. In this example, once a user deselects a state we will call the onStateDeselect function which will be covered later in this article.

// Create the state dropdown list
var stateDropdown = $("#stateDropdown").kendoMultiSelect({
	optionLabel: "Select State...",
	dataValueField: "id",
	dataTextField: "name",
	autoBind: false,
	dataSource: stateDs,
	filter: "contains",
	change: onStateChange,
	// Deselect event to remove cities if the parent state was removed by the user
	deselect: onStateDeselect,
}).data("kendoMultiSelect");//var stateDropdown...

State onChange Method

Just like the onChange method for the Kendo drop-down list, this method saves the selected values into the cityDropdown hidden form field and enables and refreshes the data in the next city multi-select.

/ ------------ onChange Event ------------
// Function to enable the last city dropdown menu
function onStateChange(e){
	// Get the next dropdown list.
	var cityDropdown = $("#cityDropdown").data("kendoMultiSelect");
	// Save the id in a hiden form in order to get at it in the next dropdown
	var id = this.value();
	// If the user selected a value, enable and refresh the next dropdown list
	if (id != '') {
		$("#selectedState").val(this.value());
		// Enable the city dropdown list.
		cityDropdown.enable();
		// Refresh the city dropdown
		cityDropdown.dataSource.read();
	}//..if (id != '') 

}//function onStateChange(e)

The Optional State onStateDeselect Function

This function is used to perform clean-up operations when a state is deselected from the state multi-select.

In our last cascading dropdown article, we reverted all of the child dropdowns to the initial value when a parent dropdown was changed (see the 'stateDropdown.select(0)' line at the very end of the code example of our previous Initializing the second state dropdown article).

Here, we need to do something similar when a state is deselected. For example, let's say a user selects the state of New York and California- and selects the city of New York and Los Angeles. If the user then deselects the state of New York, we will want to also remove the city of New York. However, we will leave the city of Los Angeles as the state of California was not deselected. 

The best way to understand what is going on is to interact with the demonstration at the top of this article. Select at least two states and at least one city from each state. After making the selections, deselect one of the states and the associated cities that you selected will also automatically be deselected as well.

To perform this cleanup, we are going to use JavaScript to inspect the data coming back from the server and dynamically re-populate the Kendo MultiSelect. Don't worry about the details of this code yet- we are going to cover this in detail in our next article- just note what the purpose of this code is.

This step is completely optional. If you don't want the complexity of this code you can simply remove the cities whenever something is deselected by keeping the cities in the list or by setting the values of the multi-select to null. See the code below.


// ------------ onDeselect Event ------------
function onStateDeselect(e) {
	/* 
	Inspect the transformed JSON JavaScript object from the datasource to determine if we should eliminate certain cities that belonged to the deselected state
	*/

	// Determine what was just deselected
	var dataItem = e.dataItem;

	// Note: the dataValueField and dataTextField are available in this struct 
	var deselectedStateId = dataItem.id;
	var deselectedState = dataItem.name;

	// Get any cities that were selected
	var selectedCities = $("#selectedCity").val();

	// Get a reference to the city dropdown. We will use this in the loop below to set its items.
	var cityDropdown = $("#cityDropdown").data("kendoMultiSelect");

	// Now get a reference to the city dropdown datasource. Here we are setting the the datasource using dropDownVarName.datasource. Note: if this code is not inside of a document ready block, you can use the var that was created when creating the datasource. In this case it would be cityDs. However, if this is inside of a ready block, you will get a 'Cannot read properties of undefined' error. This is always a factor when using code inside of a document ready block.
	var cityDs = cityDropdown.dataSource;
	// Get the underlying datasource data. Note, using the cityDs variable that we created above won't work- we need to use the full chained name here. 
	var cityData = cityDropdown.dataSource.data(); 
	// Clear the previous values in the multiSelect
	cityDropdown.value([]);

	// Fetch the data from the cityDs Kendo datasource. We can also use the read method
	cityDs.fetch(function(){
		// Create an array in order to populate multiple values 
		var cityIdList = [];
		// Loop through the data to create an array to send to the city multi-select
		for (var i = 0; i < cityData.length; i++) {
			// Get the cityId
			var cityStateId = cityData[i].state_id;
			var cityId = cityData[i].id;
			// Check to see if the stateId matches the deselected state when the selected city is found in the datasource (listFind Javascript function: listFind(list, value, delimiter))
			if (listFind(selectedCities,cityId) > 0){
				// If the city does not reside in the state that was just deselected, add it to cityIdList array using the JS push method 
				if (cityStateId != deselectedStateId){
					// Use the Javascript push method to push the city into our cityIdList array that we will use to repopulate the MultiSelect.
					cityIdList.push(cityId);
				}
			}
		}//..for (var i = 0; i < cityIdList.length; i++) 
		// Repopulate the multiselect
		cityDropdown.value(cityIdList);
	});//..cityDs.fetch(function(){
}

Alternative Deselect Function to Remove All of the Selected MultiSelect Options on Deselect

To remove all of the selected options in the Kendo MultiSelect, simply use the following code:

// ------------ onDeselect Event ------------
function onStateDeselect(e) {
	/* This function will remove all of the cities selected by the user by setting the MultiSelect value to null */
	// Get a reference to the city dropdown. 
	var cityDropdown = $("#cityDropdown").data("kendoMultiSelect");
	// Set the value to null (with an empty array)
	cityDropdown.value([]);
}

The Dependent City MultiSelect Dropdown

This multi-select is dependent upon the chosen values in the country dropdown and the state multi-select. This example has some very minor differences from the first state multi-select. One of the main differences is that since the user can select multiple states with the multi-select instead of just one when using the drop-down list, the ColdFusion logic on the server side must change to allow for multiple states to be passed in. We are also going to introduce Datasource grouping.

Introduction to Grouping Using the Kendo DataSource

When using a widget that allows the user to select multiple values, like the MultiSelect, it is nice to be able to group the data of the next dependent dropdown by the selected values. Nearly every Kendo Widget, including the MultiSelect, has the ability to group data. You are not limited to grouping the data by the dropdown value or the label- you can use any field in the JSON that is returned by the server. 

To group data, simply add the field to the JSON from the server and add that field to the Kendo UI group argument in the Kendo data source. You don't need to use grouping in your SQL- the only thing that you need is the JSON string to return the field that you want to group by, add the field that you want to group by, and the Kendo data source will perform the grouping for you.

Here, we will add grouping to group all of the cities by the chosen states.


Grouping the City MultiSelect Dropdown by the Selected State

If you want to group the city MultiSelect by the states, we need to:

  1. Add the state name column to the ColdFusion query that generates the JSON
  2. Add the new field to the group argument in the Kendo DataSource.

Server Side Logic using ColdFusion

Adding the State Name Column

To group by the state, the state field must be returned in the JSON. We are going to change the query in the getCities method in the World component on the server and join the country table to add the state name.

For Kendo MultSelects, the Query Clause Must Also Support Multiple Values

The state MultiSelect widget will either pass one or more numeric values, separated by commas when a selection is made. This selection is saved into the selectedCity hidden form and passed along using the Kendo DataSource.

This ColdFusion function takes these comma-separated values and validates the list using the justNumericList custom function to ensure that the values are numeric and do not have any empty values. This validation step is necessary as the database query will fail if there are empty or non-numeric values.

There are many ways to accomplish this, but in this example, I chose to use the justNumericList function as it was modified by James Moberg, and had initially assumed that he modified this function for his own cascading dropdowns that we are replicating. However, after creating the logic for this article, I found out that he is using this function for different purposes. 

Once the comma-separated stateIdList string has been validated, we will query the database with these values using the SQL IN keyword. Once the query has been made, the ColdFusion Query Object will be transformed into JSON using the convertCfQuery2JsonStruct method found in the CFJson component.

<cffunction name="getCitiesByStateIdListGroupByState" access="remote" returnformat="json" output="true"
		hint="Gets the world cities using a stateId list. This is a separate function to keep it isolated from the getCities function">
	<cfargument name="stateIdList" type="string" required="true" default="" />

	<cfset validatedNumericList = justNumericList(arguments.stateIdList)>

	<cfquery name="Data" datasource="cityDb">
		SELECT states.id as state_id, states.name as state, cities.id, cities.name, cities.latitude, cities.longitude 
		FROM cities
		INNER JOIN states 
		ON states.id = cities.state_id
		WHERE 0=0
		AND cities.state_id IN (<cfqueryparam value="#validatedNumericList#" cfsqltype="integer" list="yes">)
		ORDER BY cities.name
	</cfquery>

	<!--- Convert the query object into JSON using the convertCfQuery2JsonStruct method --->
	<cfinvoke component="#application.cfJsonComponentPath#" method="convertCfQuery2JsonStruct" returnvariable="jsonString">
		<cfinvokeargument name="queryObj" value="#Data#">
		<cfinvokeargument name="includeTotal" value="true">			
	</cfinvoke>

	<!--- Return it. --->
	<cfreturn jsonString>

</cffunction>

The City Kendo DataSource

The Kendo DataSource takes the values from the hidden selectedState form field and passes the comma-separated list to the getCitiesByStateIdList method. We are also grouping the data by the state name using group: { field: "state" }. This will group the data by the state in the dropdown.

This grouping is more effective when the data is not as extensive. When there are scores of cities for each state, like in this example, you will have to scroll quite a bit if the state is not the first entry in the list. 

// City populated by the second state dropdown.
var cityDs = new kendo.data.DataSource({
	transport: {
		read: {
			cache: false,
			// The function allows the url to become dynamic to append additional arguements. Here we are sending both the countryId and the stateId. There are some countries that do not have states.
			url: function() { return "<cfoutput>#application.baseUrl#</cfoutput>/demo/WorldCountries.cfc?method=getCitiesByStateIdListGroupByState&stateIdList=" + $('#selectedState').val(); },
			dataType: "json",
			contentType: "application/json; charset=utf-8", // Note: when posting json via the request body to a coldfusion page, we must use this content type or we will get a 'IllegalArgumentException' on the ColdFusion processing page.
			type: "POST"
		}//read..
	},//transport..,
	// Group by the state
	group: { field: "state" }
});//var cityDs..

Initializing the City MultiSelect 

This function is fundamentally the same as city dropDownList that we have previously covered, however, the string kendoDropDownList is replaced with kendoMultiSelect, and optionLabel is replaced with placeHolder. Also, we will not use the select argument and the end of the initialization to default the multi-select to the first value in the list (the multi-select does not have an initial value and thus does not support the select argument).

// ----------- City MultiSelect. -----------
var cityDropdown = $("#cityDropdown").kendoMultiSelect({
	placeHolder: "Select City...",
	dataTextField: "name",
	dataValueField: "id",
	autoBind: false,
	enable: false,
	filter: "contains",
	change: onCityChange,
	dataSource: cityDs
});//var kendoMultiSelect...

// Note: the select method does not exist for the multiSelect

The City onChange Method

The city onChange method simply saves the selected cities into the selectedCity hidden form and enables the button at the bottom of the UI once a selection has been made.

// ------------ onChange Event ------------
// Function to enable the button to launch a new window showing the details
function onCityChange(e){
	var id = this.value();
	// If the user selected a value, enable teh button at the end of the interface
	if (id != '') {
		// save the selected value in a hidden form
		$("#selectedCity").val(this.value());
		// Get the Kendo button at the end of the interface
		var cityButton = $("#cityButton").data("kendoButton");
		// Enable the button
		cityButton.enable(true);
	} else {
		// Disable the button at the bottom of the UI
		cityButton.enable(false);
	}//..if (id != '') {
}//function onStateChange(e)

// Create the last button.
var cityButton = $("#cityButton").kendoButton({
	enable: false
}).data("kendoButton");

Client Side HTML

The client-side HTML is straightforward. Here we have 3 hidden form fields: selectedCountry, selectedState, and the selectedCity. All of these hidden fields are populated by the widget's respective onChange events. The countryDropdown, stateDropdown, and cityDropdown fields contain the Kendo UI widgets, and the 'View City Details' button at the end of the UI in this example is for visual purposes.

<table width="100%" class="k-content">
  <input type="hidden" name="selectedCountry" id="selectedCountry" value=""/>
  <input type="text" name="selectedState" id="selectedState" value=""/>
  <input type="hidden" name="selectedCity" id="selectedCity" value=""/>
  <tr>
	<td align="left" valign="top" class="border" colspan="2"></td>
  </tr>
  <tr>
	<td align="right" style="width: 20%">
		<label for="countryDropdown">Country:</label>
	</td>
	<td>
		<!-- Create the country dropdown -->
		<select id="countryDropdown" name="countryDropdown" style="width: 95%"></select>
	</td>
  </tr>
  <tr>
	<td align="left" valign="top" class="border" colspan="2"></td>
  </tr>
   <tr>
	<td align="right" style="width: 20%">
		<label for="stateDropdown">State/Province:</label>
	</td>
	<td>
		<!-- Create the state dropdown -->
		<select id="stateDropdown" name="stateDropdown" style="width: 95%"></select>
	</td>
  </tr>
  <tr>
	<td align="left" valign="top" class="border" colspan="2"></td>
  </tr>
  <tr>
	<td align="right" style="width: 20%">
		<label for="cityDropdown">City:</label>
	</td>
	<td>
		<!-- Create the state dropdown -->
		<select id="cityDropdown" name="cityDropdown" style="width: 95%" disabled></select>
	</td>
  </tr>
  <tr>
	<td align="left" valign="top" class="border" colspan="2"></td>
  </tr>
  <tr>
	<td></td>
	<td>
		<button id="cityButton" name="cityButton" class="k-button k-primary" type="button" disabled>View City Details</button>
	</td>
  </tr>
</table>

Further Reading

This entry was posted on October 13, 2022 at 12:29 AM and has received 151 views.

ColdFusion Like JavaScript Functions


While writing an article with complex JavaScript for my next Kendo UI article, I noticed that I used some ColdFusion-like JavaScript functions to compare comma-separated lists and realized that I should first share the code. I don't want to confuse my readers and have them wonder where this JavaScript function came from or to confuse the reader by thinking that a snippet may be ColdFusion code.

I have collected these ColdFusion-like JavaScript functions over the last 20 years. I am not sure where some of these originated from- or if I wrote them myself. I believe that a few of these scripts may have originated from an old repository of JavaScripts tailored for the ColdFusion community, but I have not found this source for the last several years. I wrote or modified many of these scripts, and some of these are based on other ColdFusion custom functions and have tried my best to recognize the original source. 

If you have any functions to add or suggest revisions, please let me know!



replaceNoCase JavaScript Function

I wrote this to replicate the replaceNoCase ColdFusion function. This replaces the occurrences of substring1 with substring2 in the specified scope and is case insensitive. The scope is either 'one' or 'all' and defaults to one if not supplied.

If you want to use a case sensitive replace function, remove the 'i' flag

Example: replaceNoCase('ColdFusion is the best server-side language','ColdFusion','Lucee', 'all')

This will substitute Lucee for ColdFusion in the string 'ColdFusion is the best server-side language' and return 'Lucee is the best server-side language'.

I am not trying to degrade ACF in any way (I don't yet use Lucee), but hopefully, the Lucee fans may get a kick out of this!

// Gregory Alexander <www.gregoryalexander.com>
function replaceNoCase(string, subString, replacement, scope){
	if(scope == null) { scope = 'one'; }
	if (scope == 'all'){
		// i is a RegEx ignore case flag, g is global flag
		var regEx = new RegExp(subString, "ig");
	} else {
		// i is an RegEx ignore case flag
		var regEx = new RegExp(subString, "i");
	}
	// i is an ignore case flag, g is global flag
	var regEx = new RegExp(subString, "ig");
	var result = string.replace(regEx, replacement);
	return result;
}

listLen JavaScript function

This is a simple function that provides the length of a list and replicates the listLen ColdFusion function.

Usage: listLen(list [, delimiters ])

Example: listLen('Mount Rainier National Park,Olympic National Park,North Cascades National Park');

This will return the numeric value of 3 representing the number of National Parks in Washington State.

function listLen(list, delimiter){
	// Gregory Alexander <www.gregoryalexander.com>
	if(delimiter == null) { delimiter = ','; }
	var thisLen = list.split(delimiter);
	return thisLen.length;
}

listGetAt JavaScript Function

Gets a list value found at a certain position in a list. This should be identical to the ColdFusion listGetAt function.

Usage: listGetAt(list, position [, delimiters])

Example: listGetAt('Arches National Park,Bryce Canyon National Park,Canyonlands National Park,Capitol Reef National Park,Zion National Park', 1, ',');

This will return 'Arches National Park' which is the first element in the list. 

function listGetAt(list, position, delimiter) {
	// Gregory Alexander <www.gregoryalexander.com>
	if(delimiter == null) { delimiter = ','; }
	list = list.split(delimiter);
	if(list.length > position) {
		return list[position-1];
	} else {
		return 0;
	}
}

listFind JavaScript Function

Like the listFind ColdFusion function, this will return the index position in a list if finds the value, or return zero if nothing was found. I am not sure of the original authorship. The search is case-sensitive.

Usage: ListFind(list, value [, delimiters ])

Example: listFind('1,2,3,4,5,6','5');

This example will return a 5 as it is the 5th index in the list.

function listFind(list, value, delimiter) {
	// Adapted from a variety of sources by Gregory Alexander <www.gregoryalexander.com>

	var result = 0;
	if(delimiter == null) delimiter = ',';
	list = list.split(delimiter);
	for ( var i = 0; i < list.length; i++ ) {
		if ( value == list[i] ) {
			result = i + 1;
			return result;
		}
	}
	return result;
}

See https://copyprogramming.com/howto/what-is-the-fastest-implementation-of-coldfusion-s-listfindnocase-function-in-javascript for a different approach to this solution.


ListAppend JavaScript Function

Identical to the listAppend ColdFusion method. This function concatenates a list or element to a list and returns a string.

Usage: listAppend(list, value)

Example: listAppend('Glacier National Park', 'Yellowstone National Park');

This example will append Yellowstone National Park to the list and return 'Glacier National Park', 'Yellowstone National Park' which are the national parks within Montana.

// Adds a value to a comma-separated list. Will not add the value if the list already contains the value.
function listAppend(list, value) {
  // Adapted from a variety of sources by Gregory Alexander <www.gregoryalexander.com>
  var re = new RegExp('(^|)' + value + '(|$)');
  if (!re.test(list)) {
	return list + (list.length? ',' : '') + value;
  }
  return list;
}

listDeleteValue JavaScript function

This JavaScript function deletes a value within a list and is based on Ben Nadel's listDeleteValue function found on GitHub

Usage: listDeleteValue(list, value)

Example: listDeleteValue('Grand Canyon National Park,Saguro National Park,Indian Ocean', 'Indian Ocean');

This will delete 'Indian Ocean' from a list of parks in Arizona and will return 'Grand Canyon National Park,Saguro National Park'

// Removes a value in a comma separated list. Based on the ListDeleteValue function by Ben Nadel CF fuction https://gist.github.com/bennadel/9753040
var listDeleteValue = function(list, value){
	// Adapted from a variety of sources by Gregory Alexander <www.gregoryalexander.com>
	var values = list.split(",");
	for(var i = 0 ; i < values.length ; i++) {
		if (values[i] == value) {
			values.splice(i, 1);
			return values.join(",");
		}
	}
	return list;
}

MyDump JavaScript function that replicates the cfdump ColdFusion function

This handy function dumps out a JavaScript object to the console log. It was meant to provide functionality similar to the cfdump tag in ColdFusion. 

Usage: mydump(arr, level)

Note: this should be used carefully as it contains a lot of data which could consume a lot of resources.

// function to dump out a a javascript object.
function mydump(arr,level) {
	var dumped_text = "";
	if(!level) level = 0;

	var level_padding = "";
	for(var j=0;j<level+1;j++) level_padding += "    ";

	if(typeof(arr) == 'object') {  
		for(var item in arr) {
			var value = arr[item];

			if(typeof(value) == 'object') { 
				dumped_text += level_padding + "'" + item + "' ...
";
				dumped_text += mydump(value,level+1);
			} else {
				dumped_text += level_padding + "'" + item + "' => "" + value + ""
";
			}
		}
	} else { 
		dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
	}
	console.log(dumped_text);
}

Further Reading:

  • If you want a more comprehensive library, check out the cfjs project that has replicated 90 ColdFusion functions on GitHub.
  • James Molberg has developed a comprehensive tool to replicate the functionality of cfdump. See Javascript version of ColdFusion CFDump

This entry was posted on October 5, 2022 at 10:44 PM and has received 237 views.

Working with JSON and JavaScript


In my series of ColdFusion and Kendo UI articles, I have covered how to use JSON to populate the Kendo UI widgets. However, JSON can be used for much more than that!

JSON objects can be used by nearly every modern language, whether it is C#, Java, or ColdFusion. I personally use JSON nearly every time that I want to transfer data from the server to the client side using JavaScript.

In this article, we will take a quick break from Kendo UI and will introduce you to JSON and AJAX, show you how to create and consume JSON, how to consume JSON on the server using AJAX, and how to work with these JSON objects with JavaScript. Like our other articles, I will also provide the code and real-time examples. 



What is JSON?

Simply put, JSON is a popular string format that is used to exchange data between applications. In web applications, it is typically used to transfer data with AJAX or used when interacting with an API. 

JSON typically contains an array of structures, however, it also can be a single double-quoted string. JSON is not inherently an object but describes object data in JavaScript and other languages. However, once JSON is successfully parsed by JavaScript (or other languages), the JSON information is transformed into a native JavaScript object.


JSON Structure

The example shown below is a typical JSON structure that puts the data elements within an array of structures. However, as we mentioned before, you can also use simple strings in JSON as long as the string is enclosed by double quotes.

The following elements can be used in the JSON string:

  • strings enclosed in double quotes
  • numbers are not quoted
  • objects, typically a structure of key pairs enclosed by braces
  • arrays surrounded by square brackets.
  • boolean values do not use quotes
  • null uses null without quotes

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON for more detailed information.

Here is an example of all of these types. This example is used in Galaxie Blog to populate role dropdowns, and we will be using something quite similar in an upcoming article.

[
   {
      "Description":"All functionality.",
      "RoleId":1,
      "RoleName":"Administrator",
      "Capabilities": ["AssetEditor",
		"EditCategory",
		"EditComment",
		"EditFile",
		"EditPage",
		"EditPost",
		"EditProfile",
		"EditServerSetting",
		"EditSubscriber",
		"EditTemplate",
		"EditTheme",
		"EditUser",
		"ReleasePost"],
      "Notes":null,
      "Active":true
   }
]

JSON Data Handles and Other Extraneous Information

While not technically part of the JSON specification, some HTML5 widget libraries, such as jsGrid, require the JSON to have a data handle. The data handle in the example below is the "data": string.

Some widgets, including Kendo UI, also require the JSON to have a total structure in the JSON to display the total number of records in a grid for pagination purposes.

JSON is a flexible specification, as long as you follow the basic rules, this information can be incorporated. Extra information in the JSON can also be ignored.

JSON Example with a Data Handle

{
   "data":[
      {
         "Email":"myemail@gmail.com",
         "Description":"We have covered how to use JSON to populate Kendo UI objects, but JSON can do much more than that! JSON can be used in nearly every language, however, in this article, we will discuss how to work with JSON objects in JavaScript.",
         "BlogSortDate":"September, 16 2022 23:32:00",
         "MimeType":null,
         "PostAlias":"Working-with-JSON-and-JavaScript",
         "Released":false,
         "Body":"In my series of ColdFusion and Kendo UI articles, I have covered how to use JSON to populate the Kendo UI widgets. However, JSON can be used for much more than that!",
         "Title":"Working with JSON and JavaScript",
         "NumViews":0,
         "Date":"September, 20 2022 00:00:00",
         "FullName":"Gregory Alexander",
      }
   ]
}

JavaScript JSON Related Functions 

The following static JavaScript functions are used with JSON:


Extracting Data from a JSON String 

To extract the value of a single element in the JSON string, use variableName.key. This is identical to getting a value stored in ColdFusion structures. For example, to get the post title in the JSON above, use data.Title.

You can also use bracket notation, just as you would get the value of a ColdFusion HQL column, using variableName["key"]. Using this notation we would use data["Title"]. Both of these statements will do the same thing.


A Brief Introduction to AJAX and JSON 

There are many other ways to elicit a JSON response from the server, but this article will focus on using AJAX on the client side to send an asynchronous HTTP (Ajax) request to a ColdFusion Component or function. The ColdFusion template on the server will process the data and send a JSON response back to the calling AJAX function. We will then inspect the AJAX response and deliver information back to the user using JavaScript.

This AJAX request may be made either by a traditional AJAX statement or performed automatically using the Kendo DataSource when we declare a Kendo DataSource or initialize a Kendo UI widget. 


AJAX Automatically Transforms JSON into JavaScript

It is important to note that if you are using AJAX to consume JSON on the server, the JSON string will automatically be converted into a native JavaScript object when using "json" as the dataType argument. After the JSON string is transformed, you will need to use native JavaScript methods to get at the underlying data in the JavaScript object.


What is the Difference Between AJAX and getJSON?

You may either use jQueries AJAX or getJSON method to fetch JSON data using a get HTTP request. The getJSON function is a simplified version of jQuery's AJAX- however, underneath the hood, the two methods are the same. 

I prefer using the AJAX method as it provides more customization, in particular, I can either enable or disable caching. Technically, there are ways to disable caching using the getJSON function, but they either affect all of the AJAX statements with a global AJAX cache var or they resort to using a timestamp method which I find to be a bit kludgy.

The arguments for the getJSON function are: 

$.getJSON(url, data, success);

Parsing JSON that has been Transformed into a JavaScript Object

There are multiple ways to get the JSON keys and values in a JavaScript object. However,  the approach will differ depending on if you want to extract a single value or multiple records. 

Extracting a Single Value

If you're using a single row of data, or know the index of the row that you want to extract, you can use data[index].key

For example, to get the state name in our result, use data[0].name. JavaScript arrays start at zero, so the first row uses an index of 0. This is identical to the approach used to parse a JSON string, although using JavaScript requires that you specify an index to get the proper row.

Like JSON, you can also use the bracket notation like so:

alert(data[0]['name'])

Here is a full example with the AJAX call:

jQuery.ajax({
	type: 'post', 
	url: '<cfoutput>#application.baseUrl#</cfoutput>/demo/WorldCountries.cfc',
	data: { // method and the arguments
		method: "getStates",
		state: "Washington"
	},//..data: {
	dataType: "json",
	success: result, // calls the result function.
	// Simplified error handling
	error: function(ErrorMsg) {
	   console.log('Error' + ErrorMsg);
	}
});//..jQuery.ajax({

function result(data){
	alert(data[0].name);
}


Looping Through Multiple Records

If you have multiple records, you can loop through the JSON and retrieve an item using the following script. I am using bracket notation in this script.

for(var i=0; i < data.length; i++){
	// Get the data held in the row in the array using bracket notation
	alert(data[i]['name'])
}

A complete example with an HTML form populated by AJAX and JSON. A real-time example is provided below.

<script>
	// Get state data from the server
	jQuery.ajax({
		type: 'post', 
		url: '<cfoutput>#application.baseUrl#</cfoutput>/demo/WorldCountries.cfc',
		data: { // method and the arguments
			method: "getStates",
			countryId: 233 //United States
		},//..data: {
		dataType: "json",
		success: result, // calls the result function.
		// Simplified error handling
		error: function(ErrorMsg) {
		   console.log('Error' + ErrorMsg);
		}
	});//..jQuery.ajax({

	function result(data){
		for(var i=0; i < data.length; i++){
			// Get the name of the state held in the row in the array and push it to the form
			$("#state" + i).val(data[i]['name']);
		}//for(var i=0; i < result.data.length; i++){..
	}//function result(data){..
</script>

<p>This form is populated by AJAX and JSON</p>
<table width="100%" class="k-content">
<!--- Loop 66 times, some states are territories here --->
<cfloop from="0" to="65" index="i">
  <tr>
	<td align="left" valign="top" class="border" colspan="2"></td>
  </tr>
  <tr>
	<td align="right" style="width: 20%">
		<label for="state<cfoutput>##</cfoutput>">State:</label>
	</td>
	<td>
		<!-- Create the state text input -->
		<input type="text" id="state<cfoutput>#i#</cfoutput>" name="state<cfoutput>#i#</cfoutput>" value="" style="width: 95%">
	</td>
   </tr>
</cfloop>
   <tr>
	 <td align="left" valign="top" class="border" colspan="2"></td>
   </tr>
</table>


Inspecting the Entire Object

Finally, you may inspect the entire object using JavaScript like so:

function result(data){
	// Loop thru the outer object (data)
	for(var i=0; i < data.length; i++){
		// Get the data held in the row in the array. 
		var obj = data[i];
		// Create an inner for loop
		for(var key in obj){
			// Set the values. 
			var attrName = key;
			var attrValue = obj[key];

			alert(attrName);
			alert(attrValue);
		}
	}
}

Complete Example with AJAX:

<script>
	// Get state data from the server
	jQuery.ajax({
		type: 'post', 
		url: '<cfoutput>#application.baseUrl#</cfoutput>/demo/WorldCountries.cfc',
		data: { // method and the arguments
			method: "getStates",
			state: "Washington"
		},//..data: {
		dataType: "json",
		success: result, // calls the result function.
		// Simplified error handling
		error: function(ErrorMsg) {
		   console.log('Error' + ErrorMsg);
		}
	});//..jQuery.ajax({

	function result(data){
		// Loop thru the outer object (data)
		for(var i=0; i < data.length; i++){
			// Get the data held in the row in the array. 
			var obj = data[i];
			// Create an inner for loop
			for(var key in obj){
				// Set the values. 
				var attrName = key;
				var attrValue = obj[key];
				// Pop the values up
				alert('Attribute Name: ' + attrName);
				alert('Attribute Value: ' + attrValue);
			}//for(var key in obj){..
		}//for(var i=0; i < data.length; i++){..
	}//function result(data){..
</script>

This page retrieves the state using AJAX and will pop up an alert showing the keys and values found in the object. There should be 8 popups here.


We will use some of what we learned here today in our next article.


Further Reading

This entry was posted on September 22, 2022 at 11:22 PM and has received 152 views.




Footer Logo

Your input and contributions are welcomed!

If you have an idea, BlogCfc based code, or a theme that you have built using this site that you want to share, please contribute by making a post here or share it by contacting us! This community can only thrive if we continue to work together.

Images and Photography:

Gregory Alexander either owns the copyright, or has the rights to use, all images and photographs on the site. If an image is not part of the "Galaxie Blog" open sourced distribution package, and instead is part of a personal blog post or a comment, please contact us and the author of the post or comment to obtain permission if you would like to use a personal image or photograph found on this site.

Credits:

Portions of Galaxie Blog are powered on the server side by BlogCfc, an open source blog developed by Raymond Camden. Revitalizing BlogCfc was a part of my orginal inspiration that prompted me to design this site.

Version:

Galaxie Blog Version 3.0 (Toby's Edition) June 14th 2022 Ice theme