Ajax Class

The Ajax class is an helper class that was created to manage Ajax requests. We suggest that you should learn about the wvm pattern first before learning about Ajax class because reference could be made to it in the course of this documentation. The Ajax class handles Requests based on 3 main categories.

  1. Direct Request
  2. JSON Restriction
  3. Referred Restriction
In this documentation, we will learn and understand the meaning of these loading types and how to apply them.

Direct Request
When requests are naturally sent to urls, the raw contents of that url is returned as response. This approach suggests that all requests are returned raw whether as an http request or as an ajax request. This means that the raw data obtained by sending an http request to a page is still the same data obtained when an ajax request is forwarded. This is termed as direct loading of contents from urls. In this method, the Ajax class has no effect on responses obtained because such data is just forwarded as obtained.

JSON Restriction
JSON Restriction is set when we declare content type of data obtained as JSON (i.e application/json). This means that we expect the response obtained from a request data to be in json format. If data obtained from a request (http or ajax) is not a valid JSON string, then a ParseError is obtained. The Ajax class makes it easy for us to declare our content-type as json by calling the Ajax::isAjax(':json') or Ajax::withJson() method.

REFFERED Restriction
REFERRED restriction is applied when we set certain referer restrictions on a particular page. This restriction, when set, prevents requests that are not sent through an XMLHttpRequest referer. In this way we can most likely keep our data protected in such a way that data is obtained only when an ajax request is sent. The Ajax class provides a method "isReferred()" which helps to set this restriction.

Initializing Ajax class
The syntax for initializing the Ajax class is shown below:

Ajax initialization syntax
  use spoova\mi\core\classes\Ajax;

  new Ajax($response, $ecode);
  
    where: 
      
     $response : optional error response text
     $ecode : optional error response code 
  
    
Whenever arguments are supplied on the Ajax class, the class becomes mandated to check if the current request is ajax. However, if no arguments are supplied, then the ajax class will only create an instanceof itself without checking if the request is an ajax request. In the code above, when $emess is supplied, once the request is not an ajax request, then the $emess text will be returned with a default 401 error response code. The $ecode can also change the default 401 response into a new accepted response code. The examples below show how the Ajax class can be initialized.

Example 1a: Ajax initialization
  use spoova\mi\core\classes\Ajax;

  new Ajax();
    
In the example above, no check will be done to determine if the incoming request is an ajax request. Only the instace of the class is created.
Example 1b: Ajax initialization
  use spoova\mi\core\classes\Ajax;

  new Ajax('invalid request', 401);
    
In the example above, the ajax class will check to determine if the incoming request is an ajax request. If the incoming request is not ajax request, then the page will exit with a response code of 401 and response message in the format below:
In the example above, the ajax class will check to determine if the incoming request is an ajax request. If the incoming request is not ajax request, then the page will exit with a response code of 401 and response message in the format below:

Example 2: Invalid Request Response Message Format
  {
    "success": false,
    "error": true,
    "message": "invalid request",
    "response_code": 401
  } 
    
Although, the first argument supplied was a string (i.e "invalid request" ), this can also be an array which will be processed and returned as a json format.

Ajax Methods
Aside from Initializing our Ajax class, there are few methods provided for handling requests and request responses. These method are listed and explained below:
  • isAjax()
  • referred()
  • withJson()
  • accept()
  • setcode()
  • getcode()
isAjax
This method is used to check or set an ajax response type and it can also be used to perform both operations at once. By default, it returns a boolean of true if the current request type is XMLHttpRequest. It can also set the content type of the current file. Example is shown below

Example: isAjax
  Ajax::isAjax(); // returns true or false
  Ajax::isAjax('application/json'); // returns true or false and sets content-type 
  
  Ajax::isAjax(':json'); // shorthand for application/json 
    
The example above shows how the isAjax() method can be applied. The first code line will not set a content-type for url. However, in the second code line, the argument supplied is used to set the content-type to application/json. Also, if our content-type is application/json as in example above, we can set the argument to :json which is a shorthand argument for application/json. This shorthand argument can only be applied for application/json content type.

Example: checking request
  if( Ajax::isAjax() ) {

    //This seems to be an xmlHttpRequest

  }
    

setcode
This setcode() method is used to set a response code

Example: setcode
  $Ajax = (new Ajax);

  if( $Ajax::isAjax() ) {

    $Ajax->setcode(401); //set last response code

  }

    
The example above shows how the setcode() method can be applied. Naturally, the setcode() only sets a last response obtained. Ordinarily, this method has no effect unless used with other methods like accept() and referred which will be discussed later

getcode
This getcode() method returns the last response code set be setcode() method.

Example: getcode
  $Ajax = (new Ajax);

  if( $Ajax::isAjax() ) {

    $Ajax->setcode(401); //set last response code

  } else  {

    $Ajax->setcode(200); //set last response code
    
  }

  echo $Ajax->getcode(); // displays either 401 or 200
    
In the example above, the getcode() method will print out the last response set by the setcode() method.

referred
This referred() method is used to declare that the request of the page must have a referer url. If the url is loaded directly, then the page will automatically terminate with a predefined response type.

Example: referred
  (new Ajax)->setcode(401)->referred(); // Ensure that a referer url is sent
    
The example above shows how the referred() method is used. The 401 response code was set first using setcode() method, then the referred() method was called. If the url was loaded directly, then the referred() method will trigger an "invalid request" response, then a 401 response header code will be sent. The response message will be similar to the response message format below:

Example: Invalid request response format
    {
      "success": false,
      "error": true,
      "message": "invalid request",
      "response_code": 401
    } 
    
Alhough, the response is similar to when the Ajax class was initialized, it might be useful in cases when we don't want to initialize Ajax in referred validation mode.

withJson
This withjson() method is a good way to perform all the activities of setting json content type and also checking if request is referred all in one line. Just like instantiating the class itself, withJson accepts the same argument that the ajax __construct() function takes. This method will first set the content-type as application/json, then will go on to instantiate the class with supplied arguments. Example of usage is below:

Example: withJson
    Ajax::withJson('invalid request', 401)// Ensure that a referer url is sent
    
The example above shows how the withJson() method is used. The response message "invalid request". will be retuned along with 401 response code, if the url was loaded directly. Also a parseError will be sent if the content data returned is not a valid json format.

request
The request() method simply returns the request method of any request sent.

Example: withJson
    Ajax::request(); // returns post, get, ...etc
    

accept
This method sets the accepted request methods required for data to be obtained from the content url. These request methods are post, get, put and delete. The accept() method sets the allowed request method(s) based on these four request methods. If the request method forward does not match the list of accepted specified methods, the page will be terminated using predefined arguments (i.e response codes and messages). By default, a 401 error response is returned while an 'invalid request method' is also returned. However, these can be modified through arguments.

Example: accept
  Ajax::accept('post'); // Accept only post request methods, return 401 on error
  
  Ajax::accept(['post','get']); // Accept only post and get request methods, return 401 on error
  
  Ajax::accept(['post'], 402); // Accept only post, return 402 on error
  
  Ajax::accept(['post'], 402, ['text' => 'custom message']); // add a custom array as response message
    
The example above shows the behavioral pattern of the accept() method when used.
  • In first line, assumming a request that is not post is sent to the ajax file, then the page will terminate with a 401 response code along with "invalid request method" as response message.
  • In second line, assumming a request that is not post or get is sent to the ajax file, then the page will terminate with a 401 response code along with "invalid request method" as response message.
  • In the third line, assumming a request that is not post is sent to the ajax file, then the page will terminate with a 402 response code along with "invalid request method" as response message.
  • In the last line, assumming a request that is not post is sent to the ajax file, then the page will terminate with a 402 response code along with the supplied array (converted to json) as response message.

Example: Invalid request response format
    {
      "success": false,
      "error": true,
      "message": "invalid request",
      "response_code": 401
    } 
    
Although, the response is similar to when the Ajax class was initialized, it might be useful in cases when we don't want to initialize Ajax in referred validation mode.

The response function
The response function is used to set responses based on request code defined. This function formats its json string under four data keys which are success, error, code and message. However, this function takes three parameters and the syntax is shown below:

Syntax: response()
    response($code, $message, $modifier);
      
        where: 

          $code : header response code (e.g 404, 401)
          $message: response message (array, string, boolean, e.t.c)
          $modifier: response message modifier (boolean)
      
    
Example 1: response()
    response(401, 'invalid request');
    
    returns: 

        {
            "success": false,
            "error": true,
            "message": "invalid request",
            "response_code": 401
        }  
    
Example 2: response()
    response(200, 'valid request');
    
    returns: 

        {
            "success": true,
            "error": false,
            "message": "valid request",
            "response_code": 200
        }  
    
Example 3: response()
    response(401, 'modified message', true);
    
    returns: 

        {
            "success": true,
            "error": false,
            "message": "modified message",
            "response_code": 401
        }  
    
In the syntax above, $code is used to set the header response code. This code will also be returned in the list of data keys under the key index name "response_code" as previously seen in the examples above. The response message $message will also set the message index key. The value of $message can be of any data type. Although, "invalid request", "valid request" and "modified message" were set above, but it can also take an array or preferred data type. Mostly, this key is used to store response data obtained which can later be fetched using index key "message" The behavioral pattern of response function is to determine the type of response by using the header response code $code defined. By default, every response code starting with digit "4" or "5" are considered as errors while those starting with 200 are considered as valid requests. When the success index return as true, then the error will return as false and when the error return as true, the success key is set as false. If the $modifier is set as true just as example 3 given above, then regardless of the response header, the success key will become true and the error key will become false. However, the response header code returned will never be affected. This method only helps to ensure that when it matters, an success response will not be mistakenly assigned the value of false.