Tutorial: Script Context

Introduction

Since xajax 0.5 beta3 you can maintain the context for xajax asynchronous calls as if they were synchronous. You can now pass any JavaScript object as a parameter to the xajax request and then access that object from the server side using the ->script, ->call, ->waitFor, ->setFunction and ->wrapFunction response commands.

In addition, you can access the context object in the callback event handlers.

In the example below, you can see an example of a xajax call that sets the context (which is a javascript object containing a reference to JavaScript class).

Step one

At first we create a simple JavaScript class containing 2 methods and one property. One method for calling the xajax serverside-function and one handling the response.
<script type="text/javascript">
var clsTest = function() {
	myProperty = false;
}
clsTest.prototype = {
	myCall : function() {
		xajax.call("return_something",{parameters:[],context:this});
	},
	myReturn : function(value) {
		alert(value+' / '+this.myProperty);
	}		
}
myTest = new clsTest();
</script>

The request

The function "myCall" from above uses xajax.call to call the xajax php function and sets the context for the call to this - a reference to the current object.

In your PHP function you can now use this to call any methods (functions) or set any attributes of the given object.
function return_something() {
	$objResponse = new xajaxResponse();
	$objResponse->script("this.myProperty=true;");
	$objResponse->script("this.myReturn('Hello world!');");
	return $objResponse;		
}

Maintaining multiple contexts

Now, you might wonder if it's possible to maintain more than one object context. Of course, you can!

You can pass an object containing n references to other objects.

For instance:
xajax.call("return_something",{parameters:[],context:{object1:this,object2:xajax.$('a_div_id')}});

In PHP you can now call/set any given method/property:
$objResponse->script("this.object1.myReturn('Hello world!');");
$objResponse->script("this.object2.innerHTML('it works!');");
That's all! :)

//Steffen (q_no)