Arcana
Arcana

Reputation: 249

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);

Upvotes: 3

Views: 953

Answers (1)

helllomatt
helllomatt

Reputation: 1339

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

Upvotes: 3

Related Questions