Last active
August 29, 2015 14:06
-
-
Save enijar/14e6bf8bc0e0fe6880d2 to your computer and use it in GitHub Desktop.
PHP AJAX Form Helper Functions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* JSON response builder, useful for AJAX request | |
* forms. Provides a nice way to send messages | |
* back to the view | |
* | |
* @param $type | |
* @param $message | |
*/ | |
function response($type, $message) { | |
echo json_encode(['type' => $type, 'message' => $message]); | |
} | |
/** | |
* Only allow data from post and get to be stored in | |
* the database. Will return false if posted data | |
* does not match allowed data | |
* | |
* @param array $values | |
* @param array $allowed | |
* @return bool | |
*/ | |
function allowedData($values = [], $allowed = []) { | |
foreach($values as $key => $value) { | |
if(!in_array($key, $allowed)) return false; | |
} | |
return true; | |
} | |
// Pass through POST or GET data and specify | |
// posted data that is allowed through | |
$guarded = allowedData($_POST, [ | |
'posted_name_1', | |
'posted_name_2' | |
... | |
]); | |
// Return a response | |
if($guarded) { | |
response('success', 'Guard passed'); | |
... | |
} else { | |
response('error', 'Invalid POST data submitted'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment