Last active
March 22, 2025 19:35
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
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
Useful for sending data in a regular GET request, an AJAX GET request, or an AJAX POST request.