| 1 |
<?php |
| 2 |
/** |
| 3 |
* Ajax Response trait. |
| 4 |
* |
| 5 |
* @package Tableberg |
| 6 |
*/ |
| 7 |
|
| 8 |
namespace Tableberg\includes\traits; |
| 9 |
|
| 10 |
use function rest_authorization_required_code; |
| 11 |
|
| 12 |
/** |
| 13 |
* Trait Ajax_Response |
| 14 |
* |
| 15 |
* PHP trait for ajax responses |
| 16 |
*/ |
| 17 |
trait Ajax_Response_Trait { |
| 18 |
/** |
| 19 |
* Response data. |
| 20 |
* |
| 21 |
* @var array |
| 22 |
*/ |
| 23 |
private $response_data = array(); |
| 24 |
|
| 25 |
/** |
| 26 |
* Set message for ajax response |
| 27 |
* |
| 28 |
* @param string $message message to be sent. |
| 29 |
*/ |
| 30 |
public function set_message( $message ) { |
| 31 |
http_response_code( 200 ); |
| 32 |
$this->response_data['message'] = $message; |
| 33 |
} |
| 34 |
|
| 35 |
/** |
| 36 |
* Set error message for ajax response |
| 37 |
* |
| 38 |
* @param string $error error message to be sent. |
| 39 |
*/ |
| 40 |
public function set_error( $error ) { |
| 41 |
http_response_code( rest_authorization_required_code() ); |
| 42 |
$this->response_data['error'] = $error; |
| 43 |
} |
| 44 |
|
| 45 |
/** |
| 46 |
* Send response data as a json format |
| 47 |
* |
| 48 |
* @param bool $die close connection after sending data. |
| 49 |
*/ |
| 50 |
public function send_json( $die = true ) { |
| 51 |
header( 'Content-Type: application/json' ); |
| 52 |
echo json_encode( $this->response_data ); |
| 53 |
$this->reset_data(); |
| 54 |
|
| 55 |
if ( $die ) { |
| 56 |
die(); |
| 57 |
} |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Reset ajax data. |
| 62 |
*/ |
| 63 |
private function reset_data() { |
| 64 |
$this->response_data = array(); |
| 65 |
} |
| 66 |
|
| 67 |
/** |
| 68 |
* Append data to given key. |
| 69 |
* |
| 70 |
* @param mixed $data value. |
| 71 |
* @param string $key data key. |
| 72 |
*/ |
| 73 |
public function append_response_data( $data, $key ) { |
| 74 |
if ( ! isset( $this->response_data['data'] ) ) { |
| 75 |
$this->response_data['data'] = array(); |
| 76 |
} |
| 77 |
|
| 78 |
$this->response_data['data'] = array( $key => $data ); } |
| 79 |
} |
| 80 |
|