-2

I'm using FormData to send some data to my server

submit.click(function (event) {
    event.preventDefault();
    let formData = new FormData();

    //filling data
}

and then I would like to use $.post() to send my form to the server in this way

$.post('CreateProduct', formData);

But it doesn't work and I receive this exception

enter image description here

Otherwise when I post my data with $.ajax it works perfectly

$.ajax({
    url: 'CreateProduct',
    data: formData,
    processData: false,
    contentType: false,
    type: 'POST'
});

Is it any opportunity to use $.post instead of $.ajax? Am I miss something??

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Eugene
  • 41
  • 6

2 Answers2

0

It seems that you may encounter jQuery adding a content type header, which will cause the boundary string to be lost.

You must set the contentType option to false to force jQuery not to add a Content-Type header for you, otherwise, the boundary string will be lost. In addition, you must set the processData flag to false, otherwise, jQuery will try to convert your FormData to a string, which will fail.

And we set the contentType to false in ajax to prevent JQuery from operating on it, thereby losing the delimiter and making the server unable to parse the file normally.

Like you changed:

$.ajax({
    url: 'CreateProduct',
    data: formData,
    processData: false,
    contentType: false,
    type: 'POST'
});
Tupac
  • 2,590
  • 2
  • 6
  • 19
-1

I tried to change it in this way and it works

$.post({
    url: 'Submit',
    data: formData,
    processData: false,
    contentType: false
});

Is there any suggestions how I can improve it?

Eugene
  • 41
  • 6
  • run ```$.ajaxSetup({processData: false})``` before call $.post. you can simplity your code to ```$.post('Submit', formData)```. – Henry Trần Oct 03 '21 at 18:20
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Oct 04 '21 at 04:43