Toolkit:ajax

From Surebert wiki

Surebert makes ajax a breeze. These are the formats used when working with sb.ajax objects. See surebert documents for full details on all the options available with sb.ajax objects. These are only a few of the options avaiable to you but should cover most basic data transfer.

Contents

Response Formats

Teh type of data returned from the URL requested by the ajax instance determines the type of the response returned to the onResponse.

Plain Text/HTML

Plain Text - Loading plain text based data from the server is simple. In fact it is the default format of sb.ajax instances

javascript code

var myAjax = new sb.ajax({
	format : 'text', //this is the default - so its not required
	url : '/path/to/myServerSidePage.php',
	//optional data to send
	data : {
		name : 'joe',
		day : 'monday'
	},
	onResponse : function(response){
		//you can use this text as a string once it loads
		alert(response);
	}
});
myAjax.fetch();

Node Sync

Node sync allows you to easily sync the contents of a DOM node innerHTML to the contents of a serverside file. While you can do this yourself using the text format above and specifying the node in the onResponse function it is even easier to use the node format by specifying the node in the sb.ajax instance.

javascript code

var myAjax = new sb.ajax({
	node : '#myNodeId',
	//optional data to send
	data : {
		name : 'joe',
		day : 'monday'
	}
});
myAjax.fetch();

JSON

Javascript Object Notation - see json.org for more information. A simple way of serializing javascript objects which makes them ideal data transfer strings. Also see php 5.2's json_encode and json_decode which can turn native php objects into json objects and vice versa. If the url being fetched serves the content type of the document as "application/json", and the ajax instances format property is not set, it will automatically parse as json.

javascript code

var myAjax = new sb.ajax({
	format : 'json',
	url : '/path/to/myServerSidePage.php',
	//optional data to send
	data : {
		name : 'joe',
		day : 'monday'
	},
	onResponse : function(obj){
		//once the object arrives you can use its properties as you would with any javascript object
		alert(obj.myProperty);
	}
});
myAjax.fetch();

XML

sb.ajax instances can also easily read xml, although I would suggest moving toward a pure JSON based system as it is more bandwidth efficient and much easier to parse. If the format property on the ajax instance is not set and url fetched serves the page as "text/xml" the response object passed to the onResponse will passed as an XML node.

javascript code

var myAjax = new sb.ajax({
	format : 'xml',
	url : '/path/to/myServerSidePage.php',
	//optional data to send
	data : {
		name : 'joe',
		day : 'monday'
	},
	onResponse : function(xml){
		//would alert the ip
		alert(xml.firstChild.nodeValue);
 
		//would also alert the ip
		alert(xml.getElementsByTagName('ip')[0].nodeValue);
 
	}
});
myAjax.fetch();

Boolean

Sometimes you want to just receive true or false. If the url fetched returns content type as "boolean/value" then the result is interpreted as a boolean as passed to the instance onResponse as such. Value 0 is translated to false and 1 to true.

javascript code

var myAjax = new sb.ajax({
	url : '/path/to/myServerSidePage.php',
	//optional data to send
	data : {
		name : 'joe',
		day : 'monday'
	},
	onResponse : function(bool){
		if(bool){
			alert("it's true");
		}	
 
	}
});
myAjax.fetch();

Example PHP script

php code

header('Content-type: boolean/value');
echo 1;

Properties

format

The format the data is retreived in. Can be json, text, xml, head, js, send - s. This value overides any sb.ajax.defaultFormat value set or if the Content-type from server matches a specific format.

Possible Values

  • text - returns the data from the server side script as text and passes it to the instance's handler method
  • json - returns the data from the server side script as a JSON object whose properties can easily be accessed with javascript. This type is defaulted if the page is served with the term 'json' in the content type e.g. application/json
  • xml - returns the data from the server side script as an XML node which can be parsed with traditional XML parsing methods in javascript This type is defaulted if the page is served with the term 'xml' in the content type e.g. application/xml
  • js - evaluated the data returned from the server side script as javascript. This type is defaulted if the page is served with the term 'javascript' in the content type e.g. application/javascript
  • send - only sends data and does not receive any data
  • head - only reads the header data from the HTML transaction and passes that to the instance's onResponse method. If a header property is specified on the sb.ajax instance, then only that header is passed
  • boolean - interprets the response as boolean 1 = true, 0 = false

javascript code

var myAjax = new sb.ajax({
	url : 'process.php',
	format : 'json'
});
 
//fetches the data from the url specified
myAjax.fetch();

method

The data transport method to use "post" or "get"

data

The data property can be either a string, an array or an object As String - If the data property is a string it is sent as is.

javascript code

var aj = new sb.ajax({
	url : '/some/url',
	data : 'a=b&c=d'
});

As Array - If the data property is an array it is converted to key/value pairs e.g. ['a', 'b', 'c'] -> 0=a&1=b&2=c

javascript code

var aj = new sb.ajax({
	url : '/some/url',
	data : ['a', 'b', 'c']
});

As Object - If the data property is an object, it is converted to key/value pairs using the object property as key e.g. {fname : 'paul', lname : 'visco'} -> fname=paul&lname=visco

javascript code

var aj = new sb.ajax({
	url : '/some/url',
	data : {fname : 'paul', lname : 'visco'}
});

debug

The best way to debug is using the surebert debug consol which works in all browsers. As long as you have loaded the developer toolkit. Alternatively, you can use firebug https://addons.mozilla.org/en-US/firefox/addon/1843 which is also great. To set surebert debugging on, set the debug property of the sb.ajax instance to true and make sure that the developer module is loaded.

javascript code

sb.include('developer');
var myAjax = new sb.ajax({
	debug : 1,
	url : '/path/to/myServerSidePage.php',
	//optional data to send
	data : {
		name : 'joe',
		day : 'monday'
	},
	onResponse : function(data){
		//do something with the data
 
	}
});
myAjax.fetch();

async - synchronous requests

While AJAX stands for Asynchronous Javascript and XML, just like we don;t use it with XML sometimes, also sometimes you want the data to be fetched synchronously. Synchronous requests cause all javascript executation to halt until the data comes back from the request. This is escpecially important if you are loading new javacript function which are to be used later in the code.

Both sb.load() and in turn, sb.include() use this to load external javascript on the fly.

javascript code

var myAjax = new sb.ajax({
	async : 0, //not asynchronous
	url : '/path/to/myServerSidePage.php',
	//optional data to send
	data : {
		name : 'joe',
		day : 'monday'
	},
	onResponse : function(data){
		//do something with the data
 
	}
});
myAjax.fetch();

completed

Is set to 0 when if the ajax call is not complete or set to 1 if it is compelete. Used to check for complete state when using synchronous calls in safari. Each instances completed status is reset on each fetch() call so that asynchronous calls can still be fetched more than once.

timeout

The amount of time in milliseconds the ajax request will wait before it aborts. This is optional

javascript code

var myAjax = new sb.ajax({
	url : 'process.php',
	timeout : 1000
});
 
//fetches the data from the url specified
myAjax.fetch();

Methods

These methods are for sb.ajax instances.

abort()

Cancels a fetch in progress

javascript code

var myAjax = new sb.ajax({
	url : 'process.php'
});
myAjax.fetch();
 
//aborts a fetch already in progress, you could attach this event to a cancel button
myAjax.abort();

fetch()

Send the data and fetch the results. This is how you execute you ajax instance and grab the data from the server.

javascript code

var myAjax = new sb.ajax({
	url : 'process.php'
});
myAjax.fetch();

Event Handlers

These event handlers are for sb.ajax instances.

onAbort()

Fires when ajax fetch is aborted by .abort

javascript code

var myAjax = new sb.ajax({
	url : 'process.php',
	onAbort : function(){
		alert('sorry aborted');
	}
}).fetch();

onHeaders(status, statusText)

Fires when ajax is fetched and headers are received

javascript code

var myAjax = new sb.ajax({
	url : 'process.php',
	onHeaders : function(status, statusText){
		//alert 400 if file not found
		alert(status);
		//you also have access to other headers
		alert(this.getResponseHeader('Content-type');
	}
});

By default, onHeaders looks for an sb_on_response\d+ headers and executes the js in the headers within the scope of the ajax request. You can have as many sb_on_response headers as you want

In php you could send response headers like this:

php code

header('sb_on_response1: alert("hello");');
header('sb_on_response2: alert("bye");');

See Framework:sb_JS for examples on issuing these commands from the sb framework

onResponse(response)

Fires when the ajax request gets its response back from the server. Response can be string, json, or XML depending on ajax instance .format property. This was previously called "handler."

javascript code

var myAjax = new sb.ajax({
	url : 'process.php',
	onResponse : function(response){
		alert(response);
	}
});

onTimeout()

Fires when the timeout (optional) is reached before the data is returned from the url

javascript code

var myAjax = new sb.ajax({
	url : 'process.php',
	timeout : 1000,
	onTimeout : function(){
		alert('sorry');
	}
}).fetch();

onLog(logId, info))

Fires when the sb.ajax logs events

javascript code

var myAjax = new sb.ajax({
	url : 'process.php',
	timeout : 1000,
	onLog : function(logId, info){
		alert(info);
	}
}).fetch();

Shortcut Functions

The following shorcut functions are provided for convenience quick ajax. Data argument is optional. You can leave it out and replace its position with the callback. The data property can be any format listed above in the data section for sb.ajax (string, array, object)

send some data via post to a page and fire callback

javascript code

sb.post('/url/to', {a : 'b'}, function(r){ alert(r);});

some data get to a page and fire callback

javascript code

sb.get('/url/to', {a : 'b'}, function(r){ alert(r);});

grab data from url and put result into some element innerHTML

javascript code

sb.post('/content/testing', '#myDiv');

send data and grab data from url and put result into some element innerHTML

javascript code

sb.post('/content/testing', {a : 'b'}, '#myDiv');