Avatar

Michael Turnwall

Twitter - About.Me

View the Project on GitHub mturnwall/ajax_class

Ajax Class

Purpose

This javascript object is written to allow a developer to make ajax calls for any project without having to write custom response handlers for every project. With just a single ajax call you can update multiple parts of a page regardless if you are updating code or just content. In fact you can update code blocks on one portion of a page, content on another portion, and even form fields all with a single ajax call.

This magic is accomplished by using a standardized JSON model. This JSON model holds key:value pairs where the key is the ID of an element on a page to update and the value portion is the code or content that will be placed into the page.

Here is an example:


{
   	"head": {
    	"status": 200,
    	"data": {
        	"code": 400,
        	"message": "message that can be displayed in the browser, useful when an error occurs"
    	}
	},
	"body": {
   		"update": {
       		"html": [
	            {
	                "id": "mainTitle",
	                "value": "Title Was Updated"
	            },
	            {
	                "id": "mainPara",
	                "value": "This paragraph was updated and and it now contains some <strong>HTML</strong>."
	            }
	        ]
   		},
   		"replace": {
	        "forms": [
	            {
	                "id": "name",
	                "value": "Michael Turnwall"
	            }
	        ],
	        "content": [
	            {
	                "id": "updateMe",
	                "value": "1234567890"
	            }
	        ]
	    },
		"append": {
			"after": [
				{
					"id": "main",
					"value": [
						"<br><br><div>First div that is appended</div>",
						"<div>Another appended div element</div>"
					]
				}
			],
			"before": [
				{
					"id": "mainPara",
					"value": [
						"<div><strong>This div is appended before an element.</strong></div>"
					]
				}
			]
		}
   	}
}

Usage

Using the ajax object is very simple. Everything is done with just one function call.

DA.getData(url, [method], [parameters]);

url: this is the URL you are making the Ajax call to.
method [optional]: this is your method of choice which is usually GET or POST. Get is the default
parameters [optional]: this is an object literal so you can pass data to the server.

Requirements

Right now jQuery 1.3+ is required. A future version will make the object framework free so you can use it with your framework of choice.