Skip to content

Commit 42f6ad2

Browse files
author
BooleanType
authored
Normalizing readme.md appearance.
1 parent bbbf416 commit 42f6ad2

File tree

1 file changed

+89
-72
lines changed

1 file changed

+89
-72
lines changed

README.md

+89-72
Original file line numberDiff line numberDiff line change
@@ -11,44 +11,48 @@
1111

1212
```php
1313
if ($reg_id == '') {
14-
throw new Exception(json_encode([500, 'Error description.']));
14+
throw new Exception(json_encode([500, 'Error description.']));
1515
}
16-
if(!$someThing->save()) {
17-
throw new Exception('Something is not saved');
16+
if (!$someThing->save()) {
17+
throw new Exception('Something is not saved');
1818
}
19+
1920
```
21+
22+
2023
#### Example of pseudo-code processing an AJAX request on the server
2124
```php
2225
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') {
2427
throw new Exception(json_encode([403, 'Forbidden']));
2528
}
2629

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']);
4441
}
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+
}
4548
} catch (Exception $e) {
46-
die($e->getMessage());
49+
die($e->getMessage());
4750
}
4851
```
4952
Exception argument can be JSON-parsable string, which **must** contain status code, (**Case 1**) or just
5053
error message (**Case 2**).
5154

55+
5256
##### Case 1
5357

5458
```php
@@ -58,7 +62,8 @@ throw new Exception(json_encode([404, 'No news']);
5862
- `404` is a status code for appropriate handling on client side. Something like HTTP status codes
5963
(https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). You can choose any code you want;
6064
- `'No news'` is an example error message, which will be rendered for end user.
61-
65+
66+
6267
##### Case 2 (without status code):
6368

6469
```php
@@ -67,23 +72,28 @@ throw new Exception('Some error description');
6772

6873
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).
6974

75+
 
76+
7077
> **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.
7178
79+
 
80+
7281
#### Success answer format
7382

7483
```php
7584
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+
])
8089
);
8190
```
8291

8392
- \*1\* is **successful** status code, **required**;
8493
- \*2\* is **optional**. Data, returned by AJAX. **If data is array, it should be encoded by `json_encode()`**;
8594
- \*1\* and \*2\* arguments should be elements of encoded array (\*3\*), which is passed to `die()`.
8695

96+
8797
##### Examples:
8898
```php
8999
// Only status, without data.
@@ -103,84 +113,91 @@ Code below is a template of how AJAX requests handling on the client side can be
103113
```javascript
104114
let msgText;
105115
$.ajax({
106-
'type': 'POST',
107-
'url': url,
108-
'data': { ... }
116+
'type': 'POST',
117+
'url': url,
118+
'data': { ... }
109119

110120
}).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-
throw new TypeError(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-
throw new TypeError(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+
throw new TypeError(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+
throw new TypeError(data);
135137
}
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;
142+
143+
// DO ERROR LOGIC HERE (IF NEEDED).
144+
145+
}
146+
136147
}).fail(function (jqXHR, textStatus, errorThrown) {
137-
msgText = errorThrown;
148+
msgText = errorThrown;
138149

139-
// 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).
140151

141152
}).always(function () {
142-
// Always triggers - in done() and fail() case as well.
153+
// Always triggers - in done() and fail() case as well.
143154

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).
145156

146157
});
147158
```
159+
160+
 
148161

149162
There is AJAX handling template in example above, which takes into account all possible errors
150163
that have occurred on the server.
151164

152165
In code...
153166
```javascript
154167
if (statusCode == 200) { // If success.
155-
// DO YOUR SUCCESS LOGIC HERE!!!
168+
// DO YOUR SUCCESS LOGIC HERE!!!
156169
```
157170
... you can add *additional logic*, related to successful query, for example:
158171
```javascript
159172
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]);
163176
```
164177
You can handle any status code, which was returned from server, for example:
165178
```javascript
166179
// If server returns a lot of statuses, you can use switch() statement.
167180
if (statusCode == 200) { // If success.
168-
msgText = 'Saving was successful!';
169-
msgContainerBgColor = 'green';
181+
msgText = 'Saving was successful!';
182+
msgContainerBgColor = 'green';
170183

171184
} else if (statusCode == 404) { // Not an error, just information.
172-
msgText = 'No news';
173-
msgContainerBgColor = 'blue';
185+
msgText = 'No news';
186+
msgContainerBgColor = 'blue';
174187

175188
} else { // Status code = 500 or another.
176-
throw new TypeError(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+
throw new TypeError(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).
180193
}
181194
```
195+
 
196+
182197
`always()` method of the jqXHR object allows to implement logic, which always should be present.
183198
184-
#### Demo
199+
----
200+
### Demo
185201
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.
186-
Entrance file is `view.html`.
202+
203+
Entrance file is `view.html`.

0 commit comments

Comments
 (0)