Coding Standards AJAX

From BOARD18 Project WIKI
Jump to navigation Jump to search
Coding Standards Index edit


The BOARD18 "JavaScript to PHP interface standard" is defined here.

AJAX call Coding Standards

AJAX calls are generally made via one of two Jquery functions. The Jquery $.post() function is the preferred method and should be used whenever possible.

The $.post() Function

the following code uses the $.post() function to perform an AJAX call.

  var dataString = 'email=' + email;
  $.post("php/emailPlayerID.php", dataString, emailPlayerResult);
  return false; 

The AJAX call will be made to the emailPlayerID.php program and dataString will be passed to it. Note that dataString is a string variable formatted as a URL query string. The response from emailPlayerID.php will be processed by the callback function specified in the third parameter of the $.post function (emailPlayerResult() in the example above).

The $.getJSON() Function

If an AJAX called PHP program returns a JSON file then it may be called by the Jquery $.getJSON() function as an alternative to the $.post() function. Special error hadling capabilities are provided by this function. These may modify the callback function processing that is described below.
Note that further documentation of these differences should eventually be included here.

Callback Function Coding Standards

Each time an AJAX call is made by a JavaScript program to a PHP program a callback function is required to process the return from the PHP program .

The first three lines of every callback function, except those in board18index.js, handle login timeout situations. These lines are always:

  if (response.indexOf("<!doctype html>") !== -1) { // User has timed out.
    window.location = "access-denied.html";
  }

If the PHP program's auth.php code detects a timeout it will transfer control to the access-denied.html page. This has the result of sending the code for this page to the callback function. The first line of this code is <!doctype html>. The above three lines handle this situation.

Echo Status Return Type

Most AJAX called PHP programs use the echo command to return short text strings indicating the status of the return. Sometimes an extra short text field is concatenated to a particular such string. For example, the 'email' status return below has a player id concatenated to it.

Two status returns which should always be provided for are "success" and "fail". Most other status returns will be editing exceptions which should be reported back to the player so that he can try again.

This is an example of a valid callback function which handles this type of status return scheme. It was taken from board18index.js.

/* 
 * Function regResult is the callback function 
 * for the ajax newUser call. 
 */
function regResult(response) { 
  if (response.indexOf("<!doctype html>") !== -1) { // User has timed out.
    window.location = "access-denied.html";
  } 
  if(response === 'success') {
    $('#login #password').val('');
    $('#login :text').val('');
    $('#register form').slideUp(300);
    $('#login form').slideDown(300);
    var loginNote ='You have successfully registered. ';
    $('#lognote').text(loginNote);
  }
  else if(response === 'duplicate') {
    $("#newuser_error").text('Username is already in use.').show();  
    $("#newuser").focus();
  }
  else if(response === 'bademail') {
    $("#email_error").text('Invalid email format, please correct.').show();  
    $("#email").focus();
  }
  else if(response.substring(0,5) === 'email') {
    var logmessage = 'Player ' + response.substring(5);
    logmessage += ' is already using this email address.';
    $("#email_error").text(logmessage).show();  
    $("#email").focus();
  }
  else if(response === 'fail') {
    var errmsg1 ='Program error in newUser.php.\n';
    errmsg1 += response + 'Please contact the BOARD18 webmaster.';
    alert(errmsg1);
  }
  else {  // Something is definitly wrong in the code.
    var errmsg2 ='Invalid return code from newUser.php.\n';
    errmsg2 += response + 'Please contact the BOARD18 webmaster.';
    alert(errmsg2);
  }  
}

JSON File Return Type

Some AJAX called PHP programs use the echo command to return a JSON string. These strings should be decoded using the jQuery.parseJSON() function. This function returns a javascript object. The PHP program will always include a status return in the object with a name like "stat". Thus, for example, the decoded object, resp, should have a sub object named "resp.stat" which can be treated exactly like the status return described in the above section. If resp.stat equals "success" then the rest of the JSON object can be processed by the callback function.

PHP AJAX Coding Standards

The other end of an AJAX call is the PHP program that is being called. This section discusses the coding of such a PHP program.

There are a lot of coding aids and tutorials about AJAX and its use. This is not intended to be such a document. But BOARD18 makes extensive use of AJAX and the job of debugging and enhancing the PHP programs called via AJAX should be simplified if they all adhere to a set of common coding conventions. This is an attempt to define such a set of common coding conventions.

This material is presented in two parts. Part one discusses PHP programs called by the $.post() function. Part two discusses PHP programs called by the $.getJSON() function.

The PHP Side Of The $.post() Call

Input Acquisition Validation

The query string in the URL used to call this program should be referenced using the $_REQUEST array. The named parameters should be "cleaned" before they are used in any mySQL calls. This is an example of code that does this:

 
// Function to sanitize values received from the form. 
// Prevents SQL injection
function clean($conn, $str) {
  $str = @trim($str);
  return mysqli_real_escape_string($conn, $str);
}

//Sanitize the POST value
$email = clean($link, $_REQUEST['email']);

This prefered version of clean() uses a mysqli routine and thus will not work before the mysqli connection has been made.

Error Returns

Do not use the "or die" error handling method shown in a lot of example PHP code.
Error returns should consist of the following 3 steps:

  1. An error_log() function call to place a descriptive message in the log.
  2. An echo statement to return 'fail' to the callback function.
  3. An exit statement to terminate the program.

This is an example of such an error return:

 
$link = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$link) {
  error_log('Failed to connect to server: ' . mysqli_connect_error());
  echo 'fail';
  exit; 
}

Data Returns

Other Returns

Other returns will either be successful returns which have no data component. They should simply echo the character string 'success'. Or they will be edit failure returns. They should echo a short charcter string which describes the error. See the Echo Status Return Type section above for examples of this.

The PHP Side Of The $.getJSON() Call

To be provided at a future date.