Skip to content

Instantly share code, notes, and snippets.

@olets
Created May 26, 2021 13:15
Show Gist options
  • Save olets/ea59d1c0c5a0f6b7794b9b4e29e435c5 to your computer and use it in GitHub Desktop.
Save olets/ea59d1c0c5a0f6b7794b9b4e29e435c5 to your computer and use it in GitHub Desktop.
Append form data to a URL
/**
* Append form data to URL
* Henry Bley-Vroman, 2021
*
* Takes a URL and a form, returns a URL
* Use case: handling form submission with JS
*
* `url = (form.action, form)` and then use `url`
* `url = (url, form)` and then use `url`
*
*
* @param url
* @param form
* @returns
*/
export default function(url, form) {
const reendcodeURI = (uri) {
return encodeURI(decodeURI(uri))
}
const formData = new FormData(form)
const searchParams = new URLSearchParams(formData)
const search = [reendcodeURI(url.search), reendcodeURI(searchParams.toString())]
.filter(v => v)
.join('&')
url.search = search
return url
}
@olets
Copy link
Author

olets commented May 26, 2021

It feels like the "right" solution should involve URLSearchParams.keys() and URLSearchParams.append() but I found simply working with strings more reliable for cases where there are array params (e.g. <input name="q[]" …). The "re-encoding" is aimed at times where you can't be certain whether or not your string is encoded; it may not support all edges.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment