Last active
April 14, 2020 07:09
-
-
Save kumarasinghe/2d40da1b2663642ef2729c4609ecd5d0 to your computer and use it in GitHub Desktop.
AJAX HTML form POST
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
/* | |
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