A script can request data from a web address and use the result in the form, for example to fill fields or a Data Grid from another application's API.
For most lookups you don't need a script. A Select component can load its options from a URL, and SQL lookups bring database data into a form. See Querying JSON Based APIs and Pulling Data From SQL Into Forms. Use a script when you need something those features can't do.
Request data from another site
Use the browser's fetch function. Because the answer comes back later, the code that uses it goes inside .then(...).
This example runs from a button (Action: Custom, see Using Buttons for Custom Actions). It requests a list and fills a Data Grid items, whose components are itemName and itemCode:
fetch('https://api.example.com/items')
.then(function (response) { return response.json(); })
.then(function (result) {
// Some services return a list directly; others wrap it, for example in "rows".
var rows = Array.isArray(result) ? result : (result.rows || []);
data.items.length = 0;
rows.forEach(function (item) {
data.items.push({ itemName: item.name, itemCode: item.code });
});
})
.catch(function (error) {
console.log('The request failed', error);
});
Use the browser's developer tools (F12) to see the response. Adding console.log(result); inside .then shows its structure in the Console tab.
Request data from GlobalForms itself
To call the GlobalForms API, use Formio.makeStaticRequest with an address built from Formio.getBaseUrl(). It sends the request as the signed-in user, so it returns only what that user has permission to see.
Formio.makeStaticRequest(Formio.getBaseUrl() + '/form?limit=100').then(function (forms) {
console.log(forms.length + ' forms');
});
Don't use Formio.makeStaticRequest for other sites. It adds the user's GlobalForms sign-in token to every request, which would send that token to the other site.
Before it will work
-
Security headers. By default, GlobalForms only lets forms request data from its own address. To call another site, add it to the
connect-srcpart of the Content-Security-Policy header. See Security Headers. -
The other site must allow it. The site you call must allow requests from your GlobalForms address (CORS). If it doesn't, the browser blocks the response.
-
HTTPS. A form served over HTTPS can only call HTTPS addresses.
Scripts are part of the form definition, which every user who opens the form can read. Never put passwords, API keys or tokens in a script. If an API needs a key, call it from the server instead, for example with an SQL lookup or a form action.