# tableberg/0.5.5/includes/traits/Ajax_Response_Trait.php

Tableberg – Simple Gutenberg Table Block, version 0.5.5. 80 lines.

- Page: https://pluginprobe.com/plugins/tableberg/0.5.5/code/includes/traits/Ajax_Response_Trait.php
- Raw: https://pluginprobe.com/plugins/tableberg/0.5.5/raw/includes/traits/Ajax_Response_Trait.php
- Modified: 2024-07-09T04:39:40+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/tableberg/0.5.5/code/includes/traits/Ajax_Response_Trait.php#L10-L20`.

```php
<?php
/**
 * Ajax Response trait.
 *
 * @package Tableberg
 */

namespace Tableberg\includes\traits;

use function rest_authorization_required_code;

/**
 * Trait Ajax_Response
 *
 * PHP trait for ajax responses
 */
trait Ajax_Response_Trait {
	/**
	 * Response data.
	 *
	 * @var array
	 */
	private $response_data = array();

	/**
	 * Set message for ajax response
	 *
	 * @param string $message message to be sent.
	 */
	public function set_message( $message ) {
		http_response_code( 200 );
		$this->response_data['message'] = $message;
	}

	/**
	 * Set error message for ajax response
	 *
	 * @param string $error error message to be sent.
	 */
	public function set_error( $error ) {
		http_response_code( rest_authorization_required_code() );
		$this->response_data['error'] = $error;
	}

	/**
	 * Send response data as a json format
	 *
	 * @param bool $die close connection after sending data.
	 */
	public function send_json( $die = true ) {
		header( 'Content-Type: application/json' );
		echo json_encode( $this->response_data );
		$this->reset_data();

		if ( $die ) {
			die();
		}
	}

	/**
	 * Reset ajax data.
	 */
	private function reset_data() {
		$this->response_data = array();
	}

	/**
	 * Append data to given key.
	 *
	 * @param mixed  $data  value.
	 * @param string $key data key.
	 */
	public function append_response_data( $data, $key ) {
		if ( ! isset( $this->response_data['data'] ) ) {
			$this->response_data['data'] = array();
		}

		$this->response_data['data'] = array( $key => $data );  }
}

```
