Skip to content

Instantly share code, notes, and snippets.

@enijar
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save enijar/14e6bf8bc0e0fe6880d2 to your computer and use it in GitHub Desktop.
Save enijar/14e6bf8bc0e0fe6880d2 to your computer and use it in GitHub Desktop.
PHP AJAX Form Helper Functions
<?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