InterJinn

Development Framework For PHP

interJinnJavaScript
Class JinnHttpRequest (EXPERIMENTAL)

public class JinnHttpRequest
extends JinnBaseClass

Implements a class for handling XmlHttpRequests with the exception that the expected response is NOT XML, but rather a Javascript array declaration thus enabling simplistic field/value retrieval from the data structure. This class works in close relationship with InterJinn PHP's JinnHttpRequestService class. The response array declaration is converted to a real Javascript array before being passed to the defined handler. The handler will also receive the request object (this class) and so it is pertinent that all handlers have the following parameter prototype:

function handler( responseArray [, requestObject] )

The class currently supports the following public fields:

httpRequest The native request object to which the JinnHttpRequest class defers.
method GET or POST. The default is GET. It is not usually necessary to set this field since the necessary method will be determined by examining any set variables to be transfered to the response script.
resource The path to a script on the server that has the desired array definition response
asynchronous Whether to handle the request asynchronously or synchronously. The default is true for asynchronous.
userName The userName to pass along with the request for htaccess style authentication.
password The password to pass along with the request for htaccess style authentication.
varsGET An array of URL query vars. While this can be set directly it is probably more convenient to use setGetVar().
varsPOST An array of POST vars. While this can be set directly it is probably more convenient to use setPostVar().
varsREQUEST An array of REQUEST vars which will be serialized to a native PHP serialize string (excluding objects which will be serialized to null). While this can be set directly it is probably more convenient to use setVar().
requestHeaders Array of header key/value pairs that have been registered for the HTTP request. While this can be set directly it is probably more convenient to use setRequestHeader().
data Supporting data for the handler function such as a DOM object that causes invocation of the request. The data can be accessed via the handler method by using this.data.
handler A function to handle the request response, the request object can be accessed via 'this' (not to be confused with the XmlHttpRequest object which can be access via the second optional parameter).
errorHandler A function to handle a non-200 return status when the request has completed (such as for a 404 page not found response). This method should accept 2 parameters, the status and the error message.

The following example illustrates how to retrieve the results of a remote query from within another service that extends JinnBaseClass:

//
// Retrieve httpRequest service.
//
var request this.getService'httpRequest' );

//
// Set the page that will return the required response.
//
request.resource '//somePage.phtml';

//
// Set up some data to be passed to the response page. The vars can be
// accessed in the response page using the getHttpRequestVar() method
// of InterJinn's PHP JinnHttpRequestService.
//
request.setVar'categoryId'this.categoryId );
request.setVar'retrieveCount'this.maxListSize );

request.data     this;
request.handler  this.handleListUpdate;

requst.send();


Direct Known Subclasses

Method Summary
public JinnHttpRequest( )

Object constructor.
public abort( )

Aborts the current request.
public deleteGetVar( string   key )

Used to delete a previously assigned request URL parameter.
public deletePostVar( string   key )

Used to delete a previously assigned request POST method parameter.
public deleteRequestHeader( string   key )

Deletes the specified request hjeader from the list of registered request headers.
public deleteVar( string   key )

Used to delete a previously assigned request variable.
public array getAllResponseHeaders( )

Used to retrieve all of the headers assigned by the requested response script.
public string getGetVar( string   key )

public string getPostVar( string   key )

public string getRequestHeader( string   key )

Used to retrieve request header values that have been previously assigned.
public string getResponseHeader( string   key )

Used to retrieve a specific response header.
public mixed getVar( string   key )

Used to retrieve the value of a previously assigned request variable.
public jinnit( )

Object constructor.
public send( )

Initiates the request to the remote server.
public setGetVar( string   key , mixed   value )

Used to assign data to the request via the URL's GET method parameters.
public setPostVar( string   key , mixed   value )

Used to assign data to the request via the a POST method parameters.
public setRequestHeader( string   key , string   value )

Assigns a value to a given request header field name.
public setVar( string   key , mixed   value )

Used to assign a request variable to the request object.

Methods Inherited from JinnBaseClass
JinnBaseClass , asFloat , asInt , augmentEvent , debug , defaultForNaN , defaultValue , destroy , getArgsPunter , getClassName , getDataType , getDocument , getDocumentBody , getDocumentHead , getElement , getElementStyle , getImageBase , getInterJinnVar , getInterJinnVars , getLibrary , getPageBase , getPageRoot , getPrintData , getPrintDataPrimitive , getScreenHeight , getScreenWidth , getService , getSize , getTime , getUid , getUniqueId , getUrl , getUrlAbsolute , getUrlVar , getWindow , getWindowHeight , getWindowScrollX , getWindowScrollY , getWindowViewMaxX , getWindowViewMaxY , getWindowViewMinX , getWindowViewMinY , getWindowWidth , isDestroyed , isWindowClosed , isWindowOpen , isset , jinnfo , jinnit , libraryExists , localizeImage , localizePage , localizePath , maxValue , minValue , normalizePath , numberFormat , objectHandler , printData , rand , redirect , rgbToHex , serviceExists , setInterJinnVar , setWindow , shallowCopy , signalHandler , sprintf , trim , urlencode  

Method Details
JinnHttpRequest

public JinnHttpRequest ( )

Since:
0.9.3

Object constructor. Initializes object's properties.

Source Code
function JinnHttpRequest()
{
   
this.jinnit();
}
/*

abort

public abort ( )

Since:
0.9.3

Aborts the current request. This is only possible if the request has been made asynchronously.

Source Code
JinnHttpRequest_proto.abort = function()
{
    try
    {
        if( 
this.httpRequest )
        {
           
this.httpRequest.abort();
        }
    }
    catch( 
){}

   
this.isActive false;
}
/*

deleteGetVar

public deleteGetVar
(
     string      key
)


Parameters:
key - The name of a URL parameter to delete from the list of assigned request URL parameters.

Since:
0.9.3

Used to delete a previously assigned request URL parameter.

Source Code
JinnHttpRequest_proto.deleteGetVar = function( key )
{
   
this.varsGET['' key] = null;
}
/*

deletePostVar

public deletePostVar
(
     string      key
)


Parameters:
key - The name of a POST method parameter to delete from the list of assigned request POST method parameters.

Since:
0.9.3

Used to delete a previously assigned request POST method parameter.

Source Code
JinnHttpRequest_proto.deletePostVar = function( key )
{
   
this.varsPOST['' key] = null;
}
/*

deleteRequestHeader

public deleteRequestHeader
(
     string      key
)


Parameters:
key - The name of a request header field to delete.

Since:
0.9.3

Deletes the specified request hjeader from the list of registered request headers.

Source Code
JinnHttpRequest_proto.deleteRequestHeader = function( key )
{
   
this.requestHeaders['' key] = null;
}
/*

deleteVar

public deleteVar
(
     string      key
)


Parameters:
key - The name of a previously assigned request variable.

Since:
0.9.3

Used to delete a previously assigned request variable.

Source Code
JinnHttpRequest_proto.deleteVar = function( key )
{
   
this.varsREQUEST[key] = null;
}
/*

getAllResponseHeaders

public array getAllResponseHeaders ( )

Returns:
The response headers from the most recent response request.

Since:
0.9.3

Used to retrieve all of the headers assigned by the requested response script. If no response headers exist then null is returned.

Source Code
JinnHttpRequest_proto.getAllResponseHeaders = function()
{
    if( 
this.httpRequest )
    {
        return 
this.httpRequest.getAllResponseHeaders();
    }

    return 
null;
}
/*

getGetVar

public string getGetVar
(
     string      key
)


Parameters:
key - The name of a URL parameter to retrieve for the current request object.

Returns:
Used to retrieve the value of a previously assigned request URL parameter.

Since:
0.9.3

Source Code
JinnHttpRequest_proto.getGetVar = function( key )
{
    return 
this.varsGET['' key];
}
/*

getPostVar

public string getPostVar
(
     string      key
)


Parameters:
key - The name of a POST method parameter to retrieve for the current request object.

Returns:
Used to retrieve the value of a previously assigned request POST method parameter.

Since:
0.9.3

Source Code
JinnHttpRequest_proto.getPostVar = function( key )
{
    return 
this.varsPOST['' key];
}
/*

getRequestHeader

public string getRequestHeader
(
     string      key
)


Parameters:
key - The name of a request header field to retrieve.

Returns:
The current value of the specified request header.

Since:
0.9.3

Used to retrieve request header values that have been previously assigned.

Source Code
JinnHttpRequest_proto.getRequestHeader = function( key )
{
    return 
this.requestHeaders['' key];
}
/*

getResponseHeader

public string getResponseHeader
(
     string      key
)


Parameters:
key - The name of a specific response header to retrieve.

Returns:
Returns the requested response header.

Since:
0.9.3

Used to retrieve a specific response header. If no such header exists then null is returned.

Source Code
JinnHttpRequest_proto.getResponseHeader = function( key )
{
    if( 
this.httpRequest )
    {
        return 
this.httpRequest.getResponseHeaderkey );
    }

    return 
null;
}
/*

getVar

public mixed getVar
(
     string      key
)


Parameters:
key - The name of a previously assigned request variable.

Returns:
The value of the specified request variable.

Since:
0.9.3

Used to retrieve the value of a previously assigned request variable.

Source Code
JinnHttpRequest_proto.getVar = function( key )
{
    return 
this.varsREQUEST[key];
}
/*

jinnit

public jinnit ( )

Since:
0.9.3

Object constructor. Initializes object's properties.

Source Code
JinnHttpRequest_proto.jinnit = function()
{
   
JinnHttpRequest.superjinn.jinnit.callthis );

   
this.allowMultipleInstances true;

   
this.httpRequest    null;
   
this.method         'auto';
   
this.resource       '/foo.php';
   
this.asynchronous   true;
   
this.userName       null;
   
this.password       null;
   
this.varsGET        = new Object();
   
this.varsPOST       = new Object();
   
this.varsREQUEST    = new Object();
   
this.requestHeaders = new Object();
   
this.data           null;
   
this.handler        null;
   
this.errorHandler   null;
   
this.timeout        20;
   
this.timeoutHandler null;
   
this.isActive       false;
}
/*

send

public send ( )

Since:
0.9.3

Initiates the request to the remote server. This method does not return a value since the request may occur asynchronously in which case nothing will be known about the response until anunspecified time. The proper way to handle the response is to assign handler and errorHandler functions to the object. All of the previously set variables and headers will be processed here and used to compose the request to the remote server. Additionally the method will check for assigned POST method variables and variables set via setVar() and set the request method to POST if necessary.

Source Code
JinnHttpRequest_proto.send = function()
{
    var 
myself this;

    var 
method this.method.toLowerCase();

    var 
query = new Array();
    var 
queryString '';

    var 
post = new Array();
    var 
postString '';

    var 
httpRequest  null;

   
this.isActive true;

    if( 
navigator.appName == 'Microsoft Internet Explorer' )
    {
        try
        {
           
httpRequest = new ActiveXObject'Microsoft.XMLHTTP' );
        }
        catch( 
)
        {
           
httpRequest null;
        }
    }

    if( 
httpRequest === null )
    {
        try
        {
           
httpRequest = new XMLHttpRequest();
        }
        catch( 
)
        {
           
httpRequest null;
        }
    }

    if( 
httpRequest === null )
    {
       
myself.errorHandler.callmyselfnullnull );
    }

   
this.httpRequest httpRequest;

   
//
    // Internal dispatcher function for thread safety.
    //
   
function dispatcher()
    {
        var 
error           false;
        var 
readyState      null;
        var 
status          null;
        var 
statusText      null;
        var 
responseText    null;
        var 
responseXml     null;

        try
        {
           
readyState httpRequest.readyState;
        }
        catch( 
)
        {
           
//
            // This usually happens if the window is closed during a
            // request.
            //

           
return;
        }

        if( 
readyState != )
        {
           
//
            // No ready yet... Wheeeeeeeeeeeee!
            //

           
return;
        }

       
myself.complete true;

        try
        {
           
status httpRequest.status;
           
statusText httpRequest.statusText;
        }
        catch( 
)
        {
           
//
            // FireFox blows chunks sometimes with the following crappy
            // internal error:
            //
            // NS_ERROR_NOT_AVAILABLE
            //
            // The recommended solution is... All these try/catches :/
            //

           
if( myself.errorHandler )
            {
               
myself.errorHandler.callmyselfnullnull );
            }

            return;
        }

        if( 
status == 200 )
        {
            if( 
myself.handler )
            {
               
data = eval( httpRequest.responseText );
               
myself.handler.callmyselfdatahttpRequest );
            }
        }
        else
        {
            if( 
myself.errorHandler )
            {
               
myself.errorHandler.call(
                   
myselfhttpRequest.statushttpRequest.statusText );
            }
        }

       
myself.isActive false;
    }

    if( 
method != 'auto' && method != 'get' && method != 'post' )
    {
       
method 'auto';
    }

   
//
    // Create GET query if any params to be appended to URL.
    //
   
for( var key in this.varsGET )
    {
       
query[query.length] =
           
this.urlencodekey )
          + 
'='
         
this.urlencodethis.varsGET[key] );
    }

    if( 
query.length )
    {
       
queryString '?' query.join'&' );
    }

    if( 
method != 'get' )
    {
       
//
        // Create POST string if any data to be posted.
        //
       
for( var key in this.varsPOST )
        {
           
post[post.length] =
               
this.urlencodekey )
              + 
'='
             
this.urlencodethis.varsPOST[key] );
        }

        var 
sPhp this.getService'php' );

       
//
        // Append data to be serialized into native PHP serialize format.
        //
       
for( var key in this.varsREQUEST )
        {
           
post[post.length] =
               
'JINN_HTTP_REQUEST_DATA='
             
this.urlencodesPhp.serializethis.varsREQUEST ) );

            break;
        }

        if( 
post.length )
        {
           
postString post.join'&' );
        }
    }

    if( 
postString == '' )
    {
       
postString '';
    }
    else
    if( 
method != 'get' )
    {
       
//
        // We need to set the Content-Type if we are posting data otherwise
        // the default sent is text/xml which will result in our POSTed data
        // being ignored :/
        //
       
this.setRequestHeader(
           
'Content-Type''application/x-www-form-urlencoded' );

       
method 'post';
    }

    if( 
method == 'auto' )
    {
       
method 'get';
    }

   
httpRequest.open
   
(
       
method,
       
this.localizePagethis.resource ) + queryString,
       
this.asynchronous,
       
this.userName,
       
this.password
   
);

   
httpRequest.onreadystatechange dispatcher;

   
//
    // Set any request headers that have been registered.
    //
   
for( var key in this.requestHeaders )
    {
       
httpRequest.setRequestHeaderkeythis.requestHeaders[key] );
    }

   
this.complete false;
   
httpRequest.sendpostString );

    var 
timer = function()
    {
        if( !
myself.complete )
        {
           
myself.abort();

            if( 
myself.timeoutHandler )
            {
               
myself.timeoutHandler.callmyself );
            }
        }
    }

   
this.getWindow().setTimeouttimerthis.timeout 1000 );
}
/*

setGetVar

public setGetVar
(
     string      key ,
     mixed      value
)


Parameters:
key - The name of a URL parameter to assign to the request.
value - The value to assign to the named URL parameter.

Since:
0.9.3

Used to assign data to the request via the URL's GET method parameters. Object and array data cannot be transfered using this method-- use the more powerful JinnHttpRequest::setVar().

Source Code
JinnHttpRequest_proto.setGetVar = function( keyvalue )
{
   
this.varsGET['' key] = value;
}
/*

setPostVar

public setPostVar
(
     string      key ,
     mixed      value
)


Parameters:
key - The name of a POST method parameter to assign to the request.
value - The value to assign to the POST method parameter.

Since:
0.9.3

Used to assign data to the request via the a POST method parameters. Object and array data cannot be transfered using this method-- use the more powerful JinnHttpRequest::setVar().

Source Code
JinnHttpRequest_proto.setPostVar = function( keyvalue )
{
   
this.varsPOST['' key] = value;
}
/*

setRequestHeader

public setRequestHeader
(
     string      key ,
     string      value
)


Parameters:
key - The name of the request header field to set.
value - The value to assign to the request header field.

Since:
0.9.3

Assigns a value to a given request header field name. These will be sent along with the request when the send() method is called.

Source Code
JinnHttpRequest_proto.setRequestHeader = function( keyvalue )
{
   
this.requestHeaders['' key] = '' value;
}
/*

setVar

public setVar
(
     string      key ,
     mixed      value
)


Parameters:
key - The name of the request variable being assigned.
value - The value of the request variable being assigned.

Since:
0.9.3

Used to assign a request variable to the request object. Request variables can be scalar values or complex multi-dimensional arrays. Objects are not supported currently due to recursive issues that I'm too lazy to consider at the moment. When the request is sent variables of this type will be serialized to PHP's native serialize() format which can then be reverted using PHP's unserialize() function. This method works in harmony with JinnHttpRequestService::getHttpRequestVar().

Source Code
JinnHttpRequest_proto.setVar = function( keyvalue )
{
   
this.varsREQUEST[key] = value;
}
/*