Set AJAX Content Type with plain JavaScript (No JQuery)

I'm working on form submission with AJAX but using plain JavaScript, no external libraries.

I've been having a problem when it comes to parsing the form as the PHP doesn't seem to be parsing the data correctly.

From some research on the internet, I've seen people set the content type to "false". The problem is however, they are are using JQuery to do this and I'm not sure how I do this in plain JavaScript.

I am only submitting a file and my PHP processes forms uploaded the traditional way perfectly. The AJAX also seems to work flawlessly and I see no fault in the code. Here is my upload function.

var fd = new FormData();
fd.append("upload-file", document.getElementById('upload-file').files[0]);

var xhr = new XMLHttpRequest();

/* I add some event listeners here for progress, load, error, and abort */

xhr.open("POST", "upload.php");
xhr.send(fd);

Answers:

Answer

In order to set the content type you need to modify the request header.

I don't know which content type you'd like to set, so I've defaulted to json.

Here's how you can set it:

var fd = new FormData();
fd.append("upload-file", document.getElementById('upload-file').files[0]);

var xhr = new XMLHttpRequest();

/* I add some event listeners here for progress, load, error, and abort */

xhr.open("POST", "upload.php");
xhr.setRequestHeader("Content-type","application/json");
xhr.send(fd);

EDIT: Setting HTTP request headers from MDN

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.