|
| 1 | +# php-jquery-ajax-handling-conception |
| 2 | + |
| 3 | +#### This functionality is advice on making requests to the server through the AJAX. This is just a *template* that can be copied from project to project and which allows you to process all possible server responses, adhering to the same style throughout the project. |
| 4 | + |
| 5 | +- The technology bundle used is PHP and JavaScript, but since this is only a concept, a similar approach can be used in other programming languages. |
| 6 | + |
| 7 | +### Server side |
| 8 | +#### Requirements |
| 9 | +1. Encapsulate all code in `try… catch` statement. |
| 10 | +2. Every condition, which suggests a failure, should throw PHP Exception, for example: |
| 11 | + |
| 12 | +```php |
| 13 | +if ($reg_id == '') { |
| 14 | + throw new Exception(json_encode([500, 'Error description.'])); |
| 15 | +} |
| 16 | +if(!$someThing->save()) { |
| 17 | + throw new Exception('Something is not saved'); |
| 18 | +} |
| 19 | +``` |
| 20 | +#### Example of pseudo-code processing an AJAX request on the server |
| 21 | +```php |
| 22 | +try { |
| 23 | + if (empty($_SERVER['HTTP_X_REQUESTED_WITH']) || strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { |
| 24 | + throw new Exception(json_encode([403, 'Forbidden'])); |
| 25 | + } |
| 26 | + |
| 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'])); |
| 44 | + } |
| 45 | +} catch (Exception $e) { |
| 46 | + die($e->getMessage()); |
| 47 | +} |
| 48 | +``` |
| 49 | +Exception argument can be JSON-parsable string, which **must** contain status code, (**Case 1**) or just |
| 50 | +error message (**Case 2**). |
| 51 | + |
| 52 | +##### Case 1 |
| 53 | + |
| 54 | +```php |
| 55 | +throw new Exception(json_encode([404, 'No news']); |
| 56 | + ``` |
| 57 | + |
| 58 | +- `404` is a status code for appropriate handling on client side. Something like HTTP status codes |
| 59 | +(https://en.wikipedia.org/wiki/List_of_HTTP_status_codes). You can choose any code you want; |
| 60 | +- `'No news'` is an example error message, which will be rendered for end user. |
| 61 | + |
| 62 | +##### Case 2 (without status code): |
| 63 | + |
| 64 | +```php |
| 65 | +throw new Exception('Some error description'); |
| 66 | + ``` |
| 67 | + |
| 68 | +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 | + |
| 70 | +> **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 | +
|
| 72 | +#### Success answer format |
| 73 | + |
| 74 | +```php |
| 75 | +die( |
| 76 | + json_encode([ // *3* |
| 77 | + 200, // *1* |
| 78 | + json_encode($news) // *2* |
| 79 | + ]) |
| 80 | +); |
| 81 | + ``` |
| 82 | + |
| 83 | +- \*1\* is **successful** status code, **required**; |
| 84 | +- \*2\* is **optional**. Data, returned by AJAX. **If data is array, it should be encoded by `json_encode()`**; |
| 85 | +- \*1\* and \*2\* arguments should be elements of encoded array (\*3\*), which is passed to `die()`. |
| 86 | + |
| 87 | +##### Examples: |
| 88 | +```php |
| 89 | +// Only status, without data. |
| 90 | +die(json_encode([200])); |
| 91 | +// Successful status and $news array. |
| 92 | +die(json_encode([200, json_encode($news)])); |
| 93 | +// Successful status and appropriate message. |
| 94 | +die(json_encode([200, 'Articles were updated successfully!'])); |
| 95 | + ``` |
| 96 | + |
| 97 | +---- |
| 98 | +### Client side |
| 99 | + |
| 100 | +#### Example of handling AJAX request on client side |
| 101 | +Code below is a template of how AJAX requests handling on the client side can be organized. |
| 102 | + |
| 103 | +```javascript |
| 104 | +let msgText; |
| 105 | +$.ajax({ |
| 106 | + 'type': 'POST', |
| 107 | + 'url': url, |
| 108 | + 'data': { ... } |
| 109 | + |
| 110 | +}).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 | + |
| 135 | + } |
| 136 | +}).fail(function (jqXHR, textStatus, errorThrown) { |
| 137 | + msgText = errorThrown; |
| 138 | + |
| 139 | + // DO ERROR LOGIC OR COPY IT FROM PREVIOUS CATCH STATEMENT (IF NEEDED). |
| 140 | + |
| 141 | +}).always(function () { |
| 142 | + // Always triggers - in done() and fail() case as well. |
| 143 | + |
| 144 | + // DO LOGIC, WHICH SHOULD BE PRESENT ANYWAY - IF AJAX IS SUCCESSFUL OR FAILED (IF NEEDED). |
| 145 | + |
| 146 | +}); |
| 147 | + ``` |
| 148 | + |
| 149 | +There is AJAX handling template in example above, which takes into account all possible errors |
| 150 | +that have occurred on the server. |
| 151 | + |
| 152 | +In code... |
| 153 | +```javascript |
| 154 | +if (statusCode == 200) { // If success. |
| 155 | + // DO YOUR SUCCESS LOGIC HERE!!! |
| 156 | +``` |
| 157 | +... you can add *additional logic*, related to successful query, for example: |
| 158 | +```javascript |
| 159 | +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]); |
| 163 | +``` |
| 164 | +You can handle any status code, which was returned from server, for example: |
| 165 | +```javascript |
| 166 | +// If server returns a lot of statuses, you can use switch() statement. |
| 167 | +if (statusCode == 200) { // If success. |
| 168 | + msgText = 'Saving was successful!'; |
| 169 | + msgContainerBgColor = 'green'; |
| 170 | + |
| 171 | +} else if (statusCode == 404) { // Not an error, just information. |
| 172 | + msgText = 'No news'; |
| 173 | + msgContainerBgColor = 'blue'; |
| 174 | + |
| 175 | +} 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). |
| 180 | +} |
| 181 | +``` |
| 182 | +`always()` method of the jqXHR object allows to implement logic, which always should be present. |
| 183 | +
|
| 184 | +#### Demo |
| 185 | +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`. |
0 commit comments