dolibarr 25.0.0-alpha
inc_fetch.php
1<?php
2
9if (!defined('DOL_VERSION')) {die();}
10
11global $documentation;
12
13if ($documentation === null || !($documentation instanceof Documentation)) { return; }
14
15
16?>
17
18<div class="documentation-section">
19 <h2 id="titlesection-tool-fetch" class="documentation-title">Fetch tool</h2>
20
21 <p>
22 <code>Dolibarr.tools.fetch()</code> sends ajax requests to Dolibarr pages and handles what every module has to do otherwise:
23 </p>
24 <ul>
25 <li>The anti CSRF token is added automatically for POST, PUT, PATCH and DELETE requests (option <code>token: true</code> to add it on a GET request). It is read from the meta tag <code>anti-csrf-currenttoken</code> printed by <code>main.inc.php</code>.</li>
26 <li>Parameters are sent the way PHP reads them: arrays as <code>key[]</code>, objects as <code>key[sub]</code>, booleans as <code>1</code> / <code>0</code>.</li>
27 <li>The response is parsed according to its content type (JSON or text), or forced with option <code>responseType</code>. A text response that looks like JSON is parsed as JSON, because many Dolibarr ajax pages print JSON without JSON content type.</li>
28 <li>Responses built with the PHP class <code>JsonResponse</code> are recognized, see below.</li>
29 <li>Errors (HTTP error, network error, timeout, invalid JSON) are displayed with <code>Dolibarr.tools.setEventMessage()</code> and thrown as <code>Dolibarr.tools.fetch.Error</code> with <code>status</code> and <code>data</code> (parsed response body).</li>
30 </ul>
31 <p>
32 <b>Note:</b> the called page must define <code>NOTOKENRENEWAL</code>, otherwise each request renews the session token and the forms of the current page are refused.
33 Also note that when the token is invalid, Dolibarr does not return an HTTP error but ignores the POST parameters: your page should check its input and return an explicit error.
34 </p>
35
36 <h3>Options</h3>
37 <ul>
38 <li><code>method</code>: <code>'GET'</code> by default.</li>
39 <li><code>data</code>: object, <code>FormData</code> or <code>URLSearchParams</code>. Sent in query string for GET, in body otherwise.</li>
40 <li><code>json</code>: body sent as JSON, the token is then sent in query string.</li>
41 <li><code>token</code>: add the anti CSRF token, <code>true</code> by default except for GET and HEAD.</li>
42 <li><code>responseType</code>: <code>'auto'</code> (default), <code>'json'</code>, <code>'text'</code> or <code>'response'</code> (native Response).
43 Use <code>'json'</code> when you expect JSON: if the session has expired, Dolibarr returns the login page and you get a clear error.</li>
44 <li><code>showErrors</code>: display errors with <code>setEventMessage</code>, <code>true</code> by default.</li>
45 <li><code>timeout</code>: abort after this delay in ms, <code>0</code> (default) to wait without limit.</li>
46 <li><code>unwrap</code>: for a <code>JsonResponse</code>, return only its <code>data</code> property, <code>false</code> by default.</li>
47 <li>Any other option (<code>signal</code>, <code>cache</code>...) is passed to the native <code>fetch()</code>.</li>
48 </ul>
49
50 <?php
51 $lines = array(
52 '<script nonce="<?php print getNonce() ?>" >',
53 ' document.addEventListener(\'Dolibarr:Ready\', async function(e) {',
54 ' const url = Dolibarr.getContextVar(\'DOL_URL_ROOT\') + \'/custom/mymodule/ajax/myobject.php\';',
55 '',
56 ' // GET request, parameters in query string',
57 ' const myObject = await Dolibarr.tools.fetch.get(url, { id: 12 }, { responseType: \'json\' });',
58 '',
59 ' // POST request, token added automatically',
60 ' try {',
61 ' const result = await Dolibarr.tools.fetch.post(url, { action: \'setField\', id: 12, field: \'note_public\', value: \'Hello\' });',
62 ' Dolibarr.tools.setEventMessage(\'Saved\');',
63 ' } catch (err) {',
64 ' // Error already displayed, use err.status and err.data for specific cases',
65 ' if (err.status === 409) {',
66 ' // Object modified by someone else',
67 ' }',
68 ' }',
69 '',
70 ' // Full syntax',
71 ' await Dolibarr.tools.fetch(url, { method: \'PUT\', json: { note_public: \'Hello\' }, timeout: 10000, showErrors: false });',
72 ' });',
73 '</script>',
74 );
75 $documentation->showCode($lines, 'php'); ?>
76
77 <h3>Server side: JsonResponse</h3>
78 <p>
79 For the pages called with <code>Dolibarr.tools.fetch()</code>, use the class <code>JsonResponse</code> (<code>core/class/jsonResponse.class.php</code>).
80 Its response <code>{result, msg, newToken, data, debug}</code> is recognized by the fetch tool:
81 </p>
82 <ul>
83 <li><code>result</code> to <code>0</code> is an error, even if the HTTP status could not be set to 400 because something was already printed.</li>
84 <li><code>msg</code> is used as error message.</li>
85 <li>On success, the whole response is returned, or only <code>data</code> with option <code>unwrap: true</code>. A success <code>msg</code> is not displayed automatically.</li>
86 <li><code>newToken</code> is not used: with <code>NOTOKENRENEWAL</code> the token to use stays the one of the meta tag <code>anti-csrf-currenttoken</code>.</li>
87 </ul>
88 <?php
89 $lines = array(
90 '<?php',
91 'if (!defined(\'NOTOKENRENEWAL\')) define(\'NOTOKENRENEWAL\', \'1\');',
92 'if (!defined(\'NOREQUIREMENU\')) define(\'NOREQUIREMENU\', \'1\');',
93 'if (!defined(\'NOREQUIREHTML\')) define(\'NOREQUIREHTML\', \'1\');',
94 'if (!defined(\'NOREDIRECTBYMAINTOLOGIN\')) define(\'NOREDIRECTBYMAINTOLOGIN\', \'1\');',
95 '',
96 'require \'../../main.inc.php\';',
97 'require_once DOL_DOCUMENT_ROOT.\'/core/class/jsonResponse.class.php\';',
98 '',
99 'top_httphead(\'application/json\');',
100 '',
101 '$jsonResponse = new JsonResponse();',
102 '',
103 'if (!$user->hasRight(\'mymodule\', \'myobject\', \'write\')) {',
104 ' $jsonResponse->msg = $langs->trans(\'NotEnoughPermissions\');',
105 ' print $jsonResponse->getResponse(); // result = 0 : HTTP 400',
106 ' exit;',
107 '}',
108 '',
109 '// ... do your stuff',
110 '$jsonResponse->result = 1;',
111 '$jsonResponse->data = [\'id\' => $object->id, \'ref\' => $object->ref];',
112 'print $jsonResponse->getResponse();',
113 );
114 $documentation->showCode($lines, 'php'); ?>
115
116 <?php
117 $lines = array(
118 '<script nonce="<?php print getNonce() ?>" >',
119 ' // Returns {id, ref}, or throws with the msg of the response if result = 0',
120 ' const myObject = await Dolibarr.tools.fetch.post(url, { action: \'update\', id: 12 }, { unwrap: true });',
121 '</script>',
122 );
123 $documentation->showCode($lines, 'php'); ?>
124
125 <div class="documentation-example">
126 <script nonce="<?php print getNonce() ?>" >
127 document.addEventListener('Dolibarr:Ready', function(e) {
128 const root = Dolibarr.getContextVar('DOL_URL_ROOT');
129
130 document.getElementById('fetch-try-success').addEventListener('click', async function(e) {
131 const data = await Dolibarr.tools.fetch.get(root + '/public/langs/langs-tool-interface.php', { domain: 'main' }, { responseType: 'json' });
132 console.log('Dolibarr.tools.fetch result', data);
133 Dolibarr.tools.setEventMessage(Object.keys(data[Object.keys(data)[0]]).length + ' translations loaded, see console');
134 });
135
136 document.getElementById('fetch-try-error').addEventListener('click', async function(e) {
137 try {
138 await Dolibarr.tools.fetch.get(root + '/public/langs/page-that-does-not-exist.php');
139 } catch (err) {
140 console.log('Dolibarr.tools.fetch error', err.status, err.message);
141 }
142 });
143 });
144 </script>
145 <button id="fetch-try-success" class="button">Fetch main translations</button>
146 <button id="fetch-try-error" class="button">Fetch a page that does not exist</button>
147 </div>
148
149</div>
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
Class to manage UI documentation.
Class JsonResponse used for ajax responses in Dolibarr.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
newToken()
Return the value of token currently saved into session with name 'newtoken'.
if(!defined( 'CSRFCHECK_WITH_TOKEN'))
Build the customer statement lines (invoices and payments) with running balance.
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button