Skip to content

Instantly share code, notes, and snippets.

@stemar
Last active March 22, 2025 19:35
Show Gist options
  • Save stemar/6490d35c66b917b2068fb687aa9a125b to your computer and use it in GitHub Desktop.
Save stemar/6490d35c66b917b2068fb687aa9a125b to your computer and use it in GitHub Desktop.
Encode data into a query string for a GET or POST request, in JavaScript ES5
function encodeQueryString(params, isPostRequest) {
var query = new Array();
for (var key in params) {
if (params.hasOwnProperty(key)) {
var value = params[key];
if (Object.prototype.toString.call(value) === "[object Array]") {
for (var i = 0, n = value.length; i < n; i++) {
query.push(encodeURIComponent(key + "[]") + "=" + encodeURIComponent(value[i]));
}
} else {
query.push(encodeURIComponent(key) + "=" + encodeURIComponent(value));
}
}
}
query = query.join("&");
if (isPostRequest) {
query = query.replaceAll("%20", "+");
query = decodeURIComponent(query);
}
return query;
}
@stemar
Copy link
Author

stemar commented Mar 22, 2025

Useful for sending data in a regular GET request, an AJAX GET request, or an AJAX POST request.

@stemar
Copy link
Author

stemar commented Mar 22, 2025

var data = {name: "Dr. Jim Lee, MD", ids: [1,2,3], integer: 9, isActive: true}
encodeQueryString(data); // For a GET request
'name=Dr.%20Jim%20Lee%2C%20MD&ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3&integer=9&isActive=true'
encodeQueryString(data, true); // For a POST request
'name=Dr.+Jim+Lee,+MD&ids[]=1&ids[]=2&ids[]=3&integer=9&isActive=true'

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