ZombieChowder ZombieChowder - 4 months ago 19
Ajax Question

Ajax multipart/formdata post request

I'm trying to send a post request to a third party API via AJAX but I'm being returned these two errors which I cannot surpass or fix.


Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-provided-api-url


Here is my HTML submit form:

<div class="upload">
<h2>Select a file for upload</h2>
<form name="addProductForm" id="addProductForm" action="javascript:;" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" id="myFile">
<input type="submit" value="Submit" id ="submit-button">
</form>
</div>


Here is my jQuery code for the AJAX request:

$(document).ready(function () {
$("#addProductForm").submit(function (event) {
event.preventDefault();
var formData = $(this).serialize();

$.ajax({
url: 'https://my-provided-api-url',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
});


Thank you in advance.

Answer

Dealing with the two errors in turn:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience

This is because you're using async: false, which is incredibly bad practice. It blocks the UI thread from updating while the request is running, which looks to the user like the browser has hung. Always make your requests asynchronous and use callbacks to handle the response.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://my-provided-api-url

This is a much larger problem. The domain you're making the request to does not have CORS enabled. This means that you cannot make a request to their API through JavaScript as you will be stopped buy the Same Origin Policy. As a workaround you could make a local AJAX request to your server which then proxies the request to the third party and returns you back the data.