jQuery Ajax PUT request with Form-Data workaround

Have you ever needed to do jQuery Ajax PUT request? It’s not as hard as you think.

Recently I’ve written a simple API as part of a school project, and the front-end team supposed to access the back-end data by standard HTTP requests like GET, POST, PUT, DELETE.

My front-end team mate encountered some troubles doing jQuery Cross-Origin ajax request for POST and PUT requests that have Form Data parameters.

var myData = new FormData();
myData.append("key", "value");
$.ajax({
	url: url,
	type: "PUT",
	data: myData,
	crossDomain: true,
	contentType: "multipart/form-data",
	processData: false,
});

There are a few parts that are not so obvious,
contentType: "multipart/form-data" and  processData: false are needed to allow FormData to be transmitted as is.

Now you can get back to your code and start trying.

 

Read further:

  1. jQuery.ajax() – jQuery API Documentation.
  2. Ajax jQuery’s Ajax-Related Methods – jQuery Learning Center.
  3. FormData – Web APIs – MDN

Leave a Reply