Skip to content

Instantly share code, notes, and snippets.

@kumarasinghe
Last active April 14, 2020 07:09
Show Gist options
  • Save kumarasinghe/2d40da1b2663642ef2729c4609ecd5d0 to your computer and use it in GitHub Desktop.
Save kumarasinghe/2d40da1b2663642ef2729c4609ecd5d0 to your computer and use it in GitHub Desktop.
AJAX HTML form POST
/*
Invalid data will cause the server to silently reject your POST request.
Analyze the POST request on form submission via Chrome Dev tools.
*/
(async () => {
// create a form data object
let form = new FormData()
// populate form fields
form.append("first_name", "Jhon")
form.append("last_name", "Corner")
form.append("submit", "Submit Form") // needed by some servers
// Add a file
// create a File object by from a URL
let fileURL = 'https://upload.wikimedia.org/wikipedia/commons/thumb/3/35/Tux.svg/150px-Tux.svg.png'
let fileName = 'tux.png'
let fileType = 'image/png'
let fileObj = await fetch(fileURL)
.then(function (res) { return res.arrayBuffer() })
.then(function (buf) { return new File([buf], fileName, { type: fileType }) })
// add the file to POST request for upload
form.append("profile_picture", fileObj)
// send POST request
var request = new XMLHttpRequest()
request.open("POST", "https://mysite.com/upload.php", true)
request.send(form)
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment