Ajax and Ajax Frameworks

I have been a developer for nearly 20 years and a web developer for about 10 years. Over the years, I have considered creating a blog to share the things I have learned (and am learning) about web design and development, but I never seemed to have the time. When I began learning about web development using Ajax and Ajax Frameworks, I decided to take the time to create this blog.

My intention for this blog is to focus primarily on Ajax Frameworks, but since web development requires knowledge of many technologies, I will occasionally write about things such as CSS, Javascript, PHP, MySQL, Flash, etc.

Lately, I have been using JQuery as my primary Ajax tool. Although I have used other Ajax Frameworks in the past (Dojo Toolkit, Yahoo! User Interface Library, Scriptaculous/Prototype), JQuery has thus far been the easiest to learn. In my first few posts I will discuss some of the JQuery Plugins that I have created. Some of these include: a plugin for Google Maps (jquery.imGoogleMaps), Form validation and submission  (jquery.imValidateForm), Page Populater (jquery.imPagePopulate), and a plugin to create lists (jquery.imList).

While I am still learning about some of the other Ajax Frameworks, I hope that what I have learned will be helpful to others. Just remember, “When you can pull the pebbles from my hand…”

JQuery Plugin: imPagePopulate

Saturday, March 14th, 2009

Depending upon the number of elements on a page, retrieving data from a database and populating a web page with the data can be a very tedious task. In the past, I have always used server-based technologies (PHP, Coldfusion, etc) to populate a page. After growing tired of creating the structures over and over again, I decided to create a JQuery plugin that would do the work for me. Most of the page population plugins I have seen only populate form elements. The imPagePopulate plugin will not only populate form elements, it will populate any HTML element on a page.

You use the imPagePopluate to map the data that comes from the server with the elements on the page. To use the plugin, do the following:

?View Code JAVASCRIPT
$('#frmBasicInfo').imPagePopulate({
         data_url: '../includes/controllers/dbActionController.php',
         data: [{name: "action", value: "doGetJson"}, {name: "page", value: "members"}, {name: "member_id", value: memId} ],
         db_map: [{"name": "first_name", "db_field": "first_name", "form": true},
                        {"name": "last_name", "db_field": "last_name", "form": true},
                        {"name": "zip_code", "db_field": "zip_code", "form": true},
                        {"name": "gender", "db_field": "gender", "form": true},
                        {"name": "birth_year", "db_field": "birth_year", "form": true}],
         sub_map: [{"name": "member_music", db_map: [
                          {"name": "member_music", "db_field": "music_cat_id", "form": true, "format": [{"type": "affix", "name": "prefix", "value": "chb_"}]}]}]
         add_elements: [{"id": "frmProfile", db_map: [
                  {"name": "profile_name", "db_field": "profile_name", "form": true},
                  {"name": "address1", "db_field": "address1", "form": true},
                  {"name": "address2", "db_field": "tAddress2", "form": true},
                  {"name": "city", "db_field": "city", "form": true},
                  {"name": "state_id", "db_field": "state_id", "form": true},
                  {"name": "country_id", "db_field": "country_id", "form": true},
                  {"name": "zip_code", "db_field": "zip_code", "form": true},
                  {"name": "phone", "db_field": "phone", "form": true},
                  {"name": "website", "db_field": "website", "form": true},
                  {"name": "email", "db_field": "email", "form": true},
                  {"name": "personal_info", "db_field": "personal_info", "form": true}
         ]}]
});

‘#frmBasicInfo’: The container for the plugin is the form that you want to populate.
data_url: The URL where you will retrieve the address
data:
Any data that you want to send to the data_url. The format for this option should be:

?View Code JAVASCRIPT
[{name: "name1", value: "value1"}, {name: "name2", value: "value2"}, etc. ]

The options will be converted into name=value pairs and sent to the data_url.

The Database Map

db_map: The plugin uses the db_map option to map the data that comes back from the server. The data returned from the server must be a Json object.

?View Code JAVASCRIPT
[ { "member_id":"8", "member_type_id":"1", "first_name":"Les", "last_name":"Green", "user_name":"lesgreen
@grasshopperpebbles.com", "address1":"441 wherever st", "address2"
:"", "city":"", "state_id":"", "phone":"", "country_id":"", "zip_code":"22123", "gender":"M", "member_dir":"lesgreengrass"
, "status":"A", "join_date":"2008-11-11 08:44:46", "mod_date":"2008-11-11 08:44:46", member_music: [
{ "music_cat_id":"1", "music_desc":"80s Music" },  { "music_cat_id":"10", "music_desc":"Rock" },  {
"music_cat_id":"14", "music_desc":"R&B" },  { "music_cat_id":"15", "music_desc":"Dance/Electronic" }]}]

The db_map uses the following format to map each element on the page:

?View Code JAVASCRIPT
{"name": "first_name", "db_field": "first_name", "form": true}

name: The name of the element.
db_field: The name of the database field that is returned in the Json object.
form: Tells the plugin whether the name option is a form element (input, textarea, etc). If “form” is false, the plugin will search for any HTML element with the given name.

The Sub Map

sub_map: The sub_map option is used for repeating fields such as multiple checkboxes. In the example data above (the Json object), the “member_music” field contains all the music interest that was saved by the member. The form contains a table that displays multiple checkboxes (see imCheckBoxDB).

The plugin will use the sub_map information to populate (check) all the checkboxes that pertain to the data that was saved.

?View Code JAVASCRIPT
sub_map: [{"name": "member_music", db_map: [
                 {"name": "member_music", "db_field": "music_cat_id", "form": true, "format": [{"type": "affix", "name": "prefix", "value": "chb_"}]}]}]

name: The name of the Json member.
db_map: The beginning of the database map for the sub_map
db_field: The name of the database field that is returned in the Json object.
form: Form element (true or false).
format: The format option can be used for the sub_map or the parent db_map. In this case, the data returned contains the id (music_cat_id) and description (music_desc) of each music category as stored in the database for each user. In the example above, the id (music_cat_id) for each category is just a number:

?View Code JAVASCRIPT
{ "music_cat_id":"1", "music_desc":"80s Music" },  //etc

I don’t want to name each of the checkboxes on my form with just a number, instead I will use a prefix:

<input id=”chb_1" name="chb_1" type="checkbox" value="80s Music" />
<input id=”chb_2" name="chb_2" type="checkbox" value="Jazz" />
<input id=”chb_3" name="chb_3" type="checkbox" value="Rock" />
<input id=”chb_4" name="chb_4" type="checkbox" value="Reggae" />
<input id=”chb_5" name="chb_5" type="checkbox" value="Blues" />

Keep in mind, the plugin is searching the page for the HTML elements. So in this case, I will use the format option to let the plugin know that checkboxes have a prefix of “chb_1”.

?View Code JAVASCRIPT
[{"type": "affix", "name": "prefix", "value": "chb_"}]

type: The type option will be 1 of 2 values, “affix” or “math”.
affix: When using the “affix” option, the “name” option will be either “prefix” or “suffix”. With “prefix”, the plugin will search for prefix value + db_field value. In the example above, the db_field value is “music_cat_id”, so the plugin will search for “chb_” + 1, “chb_” + 2, etc. The plugin will check each checkbox that is listed in the result.

math: The math option is not generally used in the sub_map. This option can be used to display calculated fields using the value of the data that is returned from the server.

?View Code JAVASCRIPT
{"name": "total ", "db_field": "sold", "form": true, "format": [{"type": "math", "name": "round"}]}

In the example above, the “total” field will display rounded value of the “sold” field that is returned from the database.

The following are the math options:

round
floor
abs
multiply
divide
add
substract

When using multiply, divide, add, or subtract, you must provide an additional value. This value will be used in the calculation with the field:

?View Code JAVASCRIPT
{"name": "total ", "db_field": "sold", "form": true, "format": [{"type": "math", "name": "multiply", "value": "20"}]}

Additional Elements

add_elements: The additional elements option is used when you have multiple forms on a page. You provide the id of the form element and the db_map for the form:

?View Code JAVASCRIPT
{"id": "frmProfile", db_map: [
{"name": "profile_name", "db_field": "profile_name", "form": true}, //etc.

Success Option

You also have the option of calling a function after the page has completed populating. Adding this option is simple:

success: loadComplete

The function that you call should not be enclosed with apostrophes if it is contained within JQuery’s  $(document).ready.

?View Code JAVASCRIPT
function pageLoaded() {
	alert('I know you are a Stargate SG-1 Fan!!');
}
//
$(document).ready(function(){
	$('#frmRegister').imPagePopulate({
		data_url: 'get_data.php',
		data: [{name: "action", value: "doCalc"}],
		db_map: [{"name": "first_name", "db_field": "first_name", "form": true},
				{"name": "last_name", "db_field": "last_name", "form": true},
				{"name": "address1", "db_field": "address1", "form": true},
				{"name": "address2", "db_field": "address2", "form": true},
				{"name": "city", "db_field": "city", "form": true},
				{"name": "states", "db_field": "states", "form": true},
				{"name": "zip_code", "db_field": "zip_code", "form": true},
				{"name": "home_phone", "db_field": "home_phone", "form": true},
				{"name": "email", "db_field": "email", "form": true},
				{"name": "viewed", "db_field": "dvd_sold", "form": true, "format": [{"type": "math", "name": "multiply", "value": "3"}]},
				{"name": "hobby1", "db_field": "hobby1", "form": false},
				{"name": "hobby2", "db_field": "hobby2", "form": false}],
		add_elements: [{"id": "frmTrueLove", db_map: [
				{"name": "tFirstName", "db_field": "love_first", "form": true},
				{"name": "tLastName", "db_field": "love_last", "form": true}
		]}],
		//apostrophe’s needed
		success: 'pageLoaded'
	});
});

The Plugin can be  downloaded from Google Code or JQuery Plugins.

Click here to view examples of using the imPagePopulate plugin.

Related posts

7 Responses to “JQuery Plugin: imPagePopulate”

  • Fajar Says:


    Hi..

    I think this is nice plugin and I am need it as entry way to go more deep to learn about using jquery and it’s available plugin.

    I have a question as newbie because a still confuse and still failure to use this plugin. Can you give me simple example code for get_data.php file that will be need for feed to the form (data_url: ‘get_data.php’)

    Thankyou in advanced.

  • admin Says:


    Fajar,
    The demo section shows examples of all my plugins. The demos for imPagePopulate display the result set for each example.
  • Fajar Says:


    May get help from you to examine my testing file especially for data feed because although I have use and make my code like your example page (http://grasshopperpebbles.com/demos/jquery_plugins/imPagePopulate/basic.html) as trial in my localhost I still can’t have result like the expect, hope I don’t bother you about this, Where I can sent the file if you don’t mind? I just wondering where is my fault.

    Best regard,

  • admin Says:


    Fajar,
    I placed a new download on Google Code. This file contains the imPopulatePage plugin and the geData.php file that I used in the demo. If you have problems after using the getData.php file, I will look at your code. Les.



  • Fajar Says:


    Now I can find where is the wrong in my code for JSON data feed, it’s awsome, thank you for the help and make this plugin available :)
  • Fajar Says:


    Hi,

    Just suggestion, in function populatePage(data, db_map)
    add approx on line 113

    $(":checkbox[name=" + itm.name +"]", $this).each(function() {

    if ($(this).val() == fieldVal) {

    $(this).attr("checked", "checked");

    }

    });


    it use for populate checkbox that not build by db using sub_map, I just found this because I need to populate checkbox but always fail until I read the script for find what make that not like my expect.

    Thanks again for make this plugin available :)

  • Fajar Says:


    Hi,

    Just continue sharing.

    When you have problem in checkbox value form post because it override by previous action value that couldn’t simply reset by just click or call form reset using javascript, you can consider using this code for override my previous code post


    $(":checkbox[name=" + itm.name +"]", $this).each(function() {

    var cb = $(this).val();
    if(cb == fieldVal){
    $(this).attr("checked", "checked");

    }

    fieldVal = cb; // reset checkbox value so like the original form value setting
    });


CommentLuv Enabled