Fix form submission (#129)

* Fix check for radio and checkbox inputs

* Fix GET form submission

* Add example forms for testing

* Refactor query string building
This commit was merged in pull request #129.
This commit is contained in:
Robin North
2018-03-02 20:25:08 +00:00
committed by GitHub
parent 0c7af354fd
commit 07baae8e4d
8 changed files with 214 additions and 38 deletions

View File

@@ -1,7 +1,11 @@
var updateQueryString = require("./util/update-query-string");
module.exports = function(location, options, callback) {
options = options || {}
var requestMethod = options.requestMethod || "GET"
var requestPayload = options.requestPayloadString || null
var queryString
var requestMethod = (options.requestMethod || "GET").toUpperCase()
var requestParams = options.requestParams || null
var requestPayload = null
var request = new XMLHttpRequest()
request.onreadystatechange = function() {
@@ -24,19 +28,40 @@ module.exports = function(location, options, callback) {
callback(null, request)
}
// Add a timestamp as part of the query string if cache busting is enabled
if (this.options.cacheBust) {
location += (!/[?&]/.test(location) ? "?" : "&") + new Date().getTime()
// Prepare the request payload for forms, if available
if (requestParams && requestParams.length) {
// Build query string
queryString = (requestParams.map(function(param) {return param.name + "=" + param.value})).join("&")
switch (requestMethod) {
case "GET":
// Reset query string to avoid an issue with repeat submissions where checkboxes that were
// previously checked are incorrectly preserved
location = location.split("?")[0]
// Append new query string
location += "?" + queryString
break
case "POST":
// Send query string as request payload
requestPayload = queryString
break
}
}
request.open(requestMethod.toUpperCase(), location, true)
// Add a timestamp as part of the query string if cache busting is enabled
if (this.options.cacheBust) {
location = updateQueryString(location, "t", Date.now())
}
request.open(requestMethod, location, true)
request.timeout = options.timeout
request.setRequestHeader("X-Requested-With", "XMLHttpRequest")
request.setRequestHeader("X-PJAX", "true")
// Add the request payload if available
if (options.requestPayloadString !== undefined && options.requestPayloadString !== "") {
// Send the proper header information along with the request
// Send the proper header information for POST forms
if (requestPayload && requestMethod === "POST") {
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
}