You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: README.md
+89-72
Original file line number
Diff line number
Diff line change
@@ -11,44 +11,48 @@
11
11
12
12
```php
13
13
if ($reg_id == '') {
14
-
throw new Exception(json_encode([500, 'Error description.']));
14
+
throw new Exception(json_encode([500, 'Error description.']));
15
15
}
16
-
if(!$someThing->save()) {
17
-
throw new Exception('Something is not saved');
16
+
if(!$someThing->save()) {
17
+
throw new Exception('Something is not saved');
18
18
}
19
+
19
20
```
21
+
22
+
20
23
#### Example of pseudo-code processing an AJAX request on the server
21
24
```php
22
25
try {
23
-
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
26
+
if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
24
27
throw new Exception(json_encode([403, 'Forbidden']));
25
28
}
26
29
27
-
if (array_key_exists('id', $_POST)) {
28
-
$id = (int) $_POST['id'];
29
-
$news = News::findOne($id);
30
-
31
-
if (!is_object($news)) {
32
-
throw new Exception(json_encode([404, 'No news']);
33
-
}
34
-
// Update found record.
35
-
$news->author = 'Stephen King';
36
-
if (!$news->save()) {
37
-
throw new Exception(json_encode([404, 'Updating error']);
38
-
}
39
-
// Success (return status and encoded data).
40
-
die(json_encode([200, json_encode($news)]));
41
-
42
-
} else { // Wrong data from user.
43
-
throw new Exception(json_encode([400, 'Bad request']));
30
+
if (array_key_exists('id', $_POST)) {
31
+
$id = (int) $_POST['id'];
32
+
$news = News::findOne($id);
33
+
34
+
if (!is_object($news)) {
35
+
throw new Exception(json_encode([404, 'No news']);
36
+
}
37
+
// Update found record.
38
+
$news->author = 'Stephen King';
39
+
if (!$news->save()) {
40
+
throw new Exception(json_encode([404, 'Updating error']);
44
41
}
42
+
// Success (return status and encoded data).
43
+
die(json_encode([200, json_encode($news)]));
44
+
45
+
} else { // Wrong data from user.
46
+
throw new Exception(json_encode([400, 'Bad request']));
47
+
}
45
48
} catch (Exception $e) {
46
-
die($e->getMessage());
49
+
die($e->getMessage());
47
50
}
48
51
```
49
52
Exception argument can be JSON-parsable string, which **must** contain status code, (**Case 1**) or just
50
53
error message (**Case 2**).
51
54
55
+
52
56
##### Case 1
53
57
54
58
```php
@@ -58,7 +62,8 @@ throw new Exception(json_encode([404, 'No news']);
58
62
-`404` is a status code for appropriate handling on client side. Something like HTTP status codes
59
63
(https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). You can choose any code you want;
60
64
-`'No news'` is an example error message, which will be rendered for end user.
61
-
65
+
66
+
62
67
##### Case 2 (without status code):
63
68
64
69
```php
@@ -67,23 +72,28 @@ throw new Exception('Some error description');
67
72
68
73
In this case data parsing will fail on client side, so `catch` block in `done()` method will triggered. `msgText` variable will contain 'Some error description' string (see [Client Side](#client-side) section).
69
74
75
+
76
+
70
77
> **WARNING**: it is necessary to understand, if all operations really should throw Exceptions. Exception throwing stops code execution in `try {}` block, and further control passes to `catch()` block. That's why such operations as logging shouldn't stop all process, if writing to log table is failed.
71
78
79
+
80
+
72
81
#### Success answer format
73
82
74
83
```php
75
84
die(
76
-
json_encode([ // *3*
77
-
200, // *1*
78
-
json_encode($news) // *2*
79
-
])
85
+
json_encode([ // *3*
86
+
200, // *1*
87
+
json_encode($news) // *2*
88
+
])
80
89
);
81
90
```
82
91
83
92
-\*1\* is **successful** status code, **required**;
84
93
-\*2\* is **optional**. Data, returned by AJAX. **If data is array, it should be encoded by `json_encode()`**;
85
94
-\*1\* and \*2\* arguments should be elements of encoded array (\*3\*), which is passed to `die()`.
86
95
96
+
87
97
##### Examples:
88
98
```php
89
99
// Only status, without data.
@@ -103,84 +113,91 @@ Code below is a template of how AJAX requests handling on the client side can be
103
113
```javascript
104
114
let msgText;
105
115
$.ajax({
106
-
'type':'POST',
107
-
'url': url,
108
-
'data': { ... }
116
+
'type':'POST',
117
+
'url': url,
118
+
'data': { ... }
109
119
110
120
}).done(function (res) {
111
-
let data, statusCode;
112
-
try {
113
-
data =JSON.parse(res);
114
-
if ($.isPlainObject(data) ||$.isArray(data)) { // Should be object (or arr).
115
-
statusCode = data[0];
116
-
if (statusCode ==200) { // If success.
117
-
118
-
// DO YOUR SUCCESS LOGIC HERE!!!
119
-
120
-
} else { // Status code != 200.
121
-
thrownewTypeError(data[1]);
122
-
}
123
-
124
-
// Data is parsable, but it is not an obj/arr, as planned (for ex., '"foo"', 'true', 'null').
125
-
} else {
126
-
thrownewTypeError(data);
127
-
}
128
-
} catch (e) {
129
-
// SyntaxError exc throws, if res is unparsable (JSON.parse() failed):
130
-
// unhandled exception is thrown, which isn't related to validation (for ex., UnknownPropertyException).
131
-
msgText = (e.name=='SyntaxError') ? res :e.message;
132
-
133
-
// DO ERROR LOGIC HERE (IF NEEDED).
134
-
121
+
let data, statusCode;
122
+
try {
123
+
data =JSON.parse(res);
124
+
if ($.isPlainObject(data) ||$.isArray(data)) { // Should be object (or arr).
125
+
statusCode = data[0];
126
+
if (statusCode ==200) { // If success.
127
+
128
+
// DO YOUR SUCCESS LOGIC HERE!!!
129
+
130
+
} else { // Status code != 200.
131
+
thrownewTypeError(data[1]);
132
+
}
133
+
134
+
// Data is parsable, but it is not an obj/arr, as planned (for ex., '"foo"', 'true', 'null').
135
+
} else {
136
+
thrownewTypeError(data);
135
137
}
138
+
} catch (e) {
139
+
// SyntaxError exc throws, if res is unparsable (JSON.parse() failed):
140
+
// unhandled exception is thrown, which isn't related to validation (for ex., UnknownPropertyException).
141
+
msgText = (e.name=='SyntaxError') ? res :e.message;
// DO ERROR LOGIC OR COPY IT FROM PREVIOUS CATCH STATEMENT (IF NEEDED).
150
+
// DO ERROR LOGIC OR COPY IT FROM PREVIOUS CATCH STATEMENT (IF NEEDED).
140
151
141
152
}).always(function () {
142
-
// Always triggers - in done() and fail() case as well.
153
+
// Always triggers - in done() and fail() case as well.
143
154
144
-
// DO LOGIC, WHICH SHOULD BE PRESENT ANYWAY - IF AJAX IS SUCCESSFUL OR FAILED (IF NEEDED).
155
+
// DO LOGIC, WHICH SHOULD BE PRESENT ANYWAY - IF AJAX IS SUCCESSFUL OR FAILED (IF NEEDED).
145
156
146
157
});
147
158
```
159
+
160
+
148
161
149
162
There is AJAX handling template in example above, which takes into account all possible errors
150
163
that have occurred on the server.
151
164
152
165
In code...
153
166
```javascript
154
167
if (statusCode ==200) { // If success.
155
-
// DO YOUR SUCCESS LOGIC HERE!!!
168
+
// DO YOUR SUCCESS LOGIC HERE!!!
156
169
```
157
170
... you can add *additional logic*, related to successful query, for example:
158
171
```javascript
159
172
if (statusCode ==200) { // If success.
160
-
msgText ='Saving was successful!';
161
-
// Work with data, retrieved from server in success case.
162
-
let requestedData =JSON.parse(data[1]);
173
+
msgText ='Saving was successful!';
174
+
// Work with data, retrieved from server in success case.
175
+
let requestedData =JSON.parse(data[1]);
163
176
```
164
177
You can handle any status code, which was returned from server, for example:
165
178
```javascript
166
179
// If server returns a lot of statuses, you can use switch() statement.
167
180
if (statusCode ==200) { // If success.
168
-
msgText ='Saving was successful!';
169
-
msgContainerBgColor ='green';
181
+
msgText ='Saving was successful!';
182
+
msgContainerBgColor ='green';
170
183
171
184
} elseif (statusCode ==404) { // Not an error, just information.
172
-
msgText ='No news';
173
-
msgContainerBgColor ='blue';
185
+
msgText ='No news';
186
+
msgContainerBgColor ='blue';
174
187
175
188
} else { // Status code = 500 or another.
176
-
thrownewTypeError(data[1]);
177
-
// Don't do error logic here
178
-
// (defining msgText and msgContainerBgColor variables, etc.);
179
-
// do it in catch() block instead (like in full example above).
189
+
thrownewTypeError(data[1]);
190
+
// Don't do error logic here
191
+
// (defining msgText and msgContainerBgColor variables, etc.);
192
+
// do it in catch() block instead (like in full example above).
180
193
}
181
194
```
195
+
196
+
182
197
`always()` method of the jqXHR object allows to implement logic, which always should be present.
183
198
184
-
#### Demo
199
+
----
200
+
### Demo
185
201
Working demo can be found in `demo` directory of current project. Code in that project is just an example, so, you can modify it according to your needs.
0 commit comments