/
ajaxresponse.php
97 lines (85 loc) · 2.05 KB
/
ajaxresponse.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
<?php
/**
* @package Habari
*
* @property integer $response_code The HTTP response code to send with the message
* @property string $message The message to return
* @property callback $callback The function to be called with the message
* @property mixed $data Data to return with the message
*/
namespace Habari;
/**
* Handles creating ajax responses, creating them in the standard format.
*
*/
class AjaxResponse
{
public $data;
private $response_code;
private $message;
private $callback = null;
private $html = null;
/* By default, we have a successful operation, with no data to return. */
function __construct( $response_code = 200, $message = null, $data = null )
{
$this->response_code = $response_code;
$this->message = $message;
$this->data = $data;
}
public function __set( $var, $val )
{
switch ( $var ) {
case 'response_code':
case 'message':
case 'data':
case 'callback':
$this->$var = $val;
break;
}
}
public function __get( $var )
{
switch ( $var ) {
case 'response_code':
case 'message':
case 'data':
case 'callback':
return $this->$var;
break;
}
}
public function html( $name, $value )
{
if ( empty( $this->html ) ) {
$this->html = array( $name => $value );
}
else {
$this->html[$name] = $value;
}
}
public function out( $to_iframe = false )
{
$ret_array = array(
'response_code' => $this->response_code,
'message' => $this->message,
'data' => $this->data,
);
// if some callback js has been provided, include that too.
if ( $this->callback != null ) {
$ret_array['habari_callback'] = $this->callback;
}
if ( !empty( $this->html ) ) {
$ret_array['html'] = $this->html;
}
// If the output is destined for an iframe, set appropriate headers we
// know the browser will definitely be able to interpret.
// See discussion at https://github.com/habari/habari/issues/204
if ( $to_iframe ) {
header( 'Content-type: text/plain' );
} else {
header( 'Content-type: application/json' );
}
echo json_encode( $ret_array );
}
}
?>