0

Add Submission to Form

by
Published Sep 27, 2024

Submit data to form using the API.

Script jotform Verified

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 621 days ago
1
type Jotform = {
2
	apiKey: string
3
	baseUrl: string
4
}
5

6
export async function main(
7
	resource: Jotform,
8
	formId: string,
9
	submissionData: {
10
		answers: {
11
			[questionId: string]: {
12
				answer: string | { [key: string]: string }
13
			}
14
		}
15
	}
16
) {
17
	const queryParams = new URLSearchParams({ apiKey: resource.apiKey })
18

19
	const endpoint = `${resource.baseUrl}/form/${formId}/submissions?${queryParams.toString()}`
20

21
	// Construct the URLSearchParams body
22
	const bodyParams = new URLSearchParams()
23

24
	// Add answers to the bodyParams
25
	Object.entries(submissionData.answers).forEach(([questionId, { answer }]) => {
26
		if (typeof answer === 'object') {
27
			// Handle cases where the answer is a complex object, like multiple fields in a question
28
			Object.entries(answer).forEach(([key, value]) => {
29
				bodyParams.append(`submission[${questionId}][${key}]`, value)
30
			})
31
		} else {
32
			// Handle simple answer strings
33
			bodyParams.append(`submission[${questionId}]`, answer)
34
		}
35
	})
36

37
	// Send the request with the URL-encoded body
38
	const response = await fetch(endpoint, {
39
		method: 'POST',
40
		headers: {
41
			'Content-Type': 'application/x-www-form-urlencoded'
42
		},
43
		body: bodyParams.toString()
44
	})
45

46
	if (!response.ok) {
47
		throw new Error(`HTTP error! status: ${response.status}`)
48
	}
49

50
	const data = await response.json()
51

52
	return data
53
}
54