So I wrote this class to handle my ajax calls simply:
ajaxCon.php:
class ajaxCon{
private $init = false;
private $functionArray = array();
private $Message = false;
private $function = null;
private $arguments = null;
private $post = null;
public function __construct(){
if(!isset($_POST['ajaxRequest'], $_POST['ajaxFunction'])) return;
$this->init = true;
ob_start();
$this->post = $this->sanitizeArr($_POST);
$this->arguments = $this->sanitizeArr($_POST['arguments']);
$this->function = $_POST['ajaxFunction'];
}
public function addFunction($functionName, $functionCode){
if(!$this->init || !isset($functionName, $functionCode) || $functionName != $this->function) return $this;
$this->Message = call_user_func_array($functionCode, $this->arguments) ? 'success' : 'fail' ;
unset($this->init, $this->functionArray, $this->post);
$returnVars = get_object_vars($this);
ob_clean();
echo json_encode($returnVars);
ob_flush();
exit();
}
private function sanitizeArr($returnArr, $sanitizer = 'sanitize_sql_string') {
array_walk_recursive($returnArr, function (&$value) use ($sanitizer) {
$value = $sanitizer($value);
});
return $returnArr;
}
}
ajaxCon.js:
function ajax() {
this.callback = false;
this.ajaxFailure = function (returnData) {};
this.ajaxSuccess = function (returnData) {};
this.call = function(functionName, argumentArray, callback){
$.ajax( $.extend(true, {}, this.ajaxSettings, {data:{'ajaxFunction':functionName, 'arguments':argumentArray}} ) );
this.callback = callback;
};
this.ajaxReturn = function (returnData){
returnData = returnData.substring(returnData.indexOf("{") - 1);
returnData = returnData.substring(0, returnData.lastIndexOf("}") + 1);
var responseArray = $.parseJSON(returnData);
if (responseArray.Message.toLowerCase() != "success"){
this.ajaxFailure(responseArray);
return;
}
this.ajaxSuccess(responseArray);
if(this.callback != false) this.callback(responseArray);
};
window.ajaxCon = this;
this.ajaxSettings = { url: window.location.href, type: 'POST', cache: false, data: {ajaxRequest: true}, success: function (returnData) {
ajaxCon.ajaxReturn(returnData)
}};
}
and you call it like so:
<?php
$ajaxCon = new ajaxCon;
$ajaxCon->addFunction('checkEmail', function($Email){
global $ajaxCon;
if(emailIsInDB($Email)) $ajaxCon->hasAccount = true;
return true;
});
?>
<script type="text/javascript">
var ajaxCon = new ajaxCon();
function checkEmail() {
ajaxCon.call('checkEmail', {'Email':$('#Email').val()}, function(result){
if(!result.hasAccount) $('#SignUp').submit();
});
}
</script>
The drawbacks I know of are lot's of preprocessing (The entire page has to be preprocesed) and the page then executes as normal until the php function I need is defined and called.
Any ideas on how I can optimize the code and make it run more efficiently while preserving/improving readability?