Error when trying to send FormData with jQuery.ajax - javascript

I have a file which I want to send to the server. The file is being passed within a FormData object and not as a path URI. This is the code I am using:
let formData = new FormData();
formData.append('enctype', 'multipart/form-data');
formData.append('mode', 'fileInsert');
formData.append('conId', 'asdasd5535asf');
formData.append('user', 'user2422424');
formData.append('filesNumber', 1);
formData.append('msgType', 'fil');
formData.append('file0', file);
$.ajax({
data: formData,
success: function (a, s) {
debugger;
}
});
When the code reaches the $.ajax call it throws this error:
Uncaught TypeError: Illegal invocation
What is wrong? Note that the jQuery AJAX is being configured earlier, with post type, URL and such.

You need to set the following properties on your AJAX request:
contentType: false,
processData: false
Setting contentType to false stops the content-type header being set. Similarly, setting processData to false will stop the content of the request being encoded, which is needed when sending a FormData object.
For more information on these and other $.ajax properties, see the jQuery Documentation

Related

JQuery: Wrong form data encoding in AJAX request

I am trying execute this simple AJAX request with JQuery:
const data = new FormData();
data.append("foo", "bar");
$.ajax({
url: "http://localhost:8080/example",
type: "post",
data: data,
processData: false
});
I check request by Google Chrome developer tools. I see that Content-type is application/x-www-form-urlencoded; charset=UTF-8 which is expected, but actual data sent in multipart encoding:
------WebKitFormBoundaryEzaaFpNlUo3QpKe1
Content-Disposition: form-data; name: "foo"
bar
------WebKitFormBoundaryEzaaFpNlUo3QpKe1--
Of course my backend application doesn't expect such encoding and fails. What is wrong and how to force JQuery to send data in urlencoded format? I tried pass extra headers or contentType options, but nothing works.
u should also add contentType: false
$.ajax({
url: "http://localhost:8080/example",
type: "post",
data: data,
processData: false,
contentType: false,
success: function (data) {
}
});
FormData is always sent as multipart/form-data. It's usually used when you're uploading a file or blob, which can't be URL-encoded.
If you want URL-encoded, don't use FormData. Use a regular object, and jQuery will encode it properly.
const data = {foo: "bar"};
Also, don't use processData: false when you're doing this.

JQuery ajax form submit for return file giving undefined error response [duplicate]

This question already has answers here:
Download pdf file using jquery ajax
(5 answers)
Closed 4 years ago.
Due to various issues with security of file manipulation, I am forced to submit the request via Ajax post method call. The server side URL receives this and gives out a pdf file as response. Server side code in java servlet is as below.
ServletOutputStream out = response.getOutputStream();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + outFile);
//create the pdf file
response.flushBuffer();
On the client side, the javascript code is sending call to a POST which calls the above code via doPost. When the form is submitted through form.submit(), the file gets downloaded nicely as pdf file. When trying through Ajax call, it is giving me undefined response under error section. Client side code as below.
var formData = new FormData();
//Fill formData with fields and files
console.log('Posting form from ajax');
$.ajax({
url: "/createPdf",
type: "POST",
data: formData,
contentType: false,
processData: false,
xhrFields: {
responseType: 'blob'
},
success: function (response, status, xhr) {
console.log('Processing response');
download(response, "merged.pdf", "application/pdf" );
},
error: function (xhr, status, error)
{
var err = xhr.responseText;
alert(err);
}
In the above, it is not going under success response. It is going under error and alerting as undefined. What am I doing wrong here. My jquery version is 1.8.0.min.js if that matters. download function refers to http://danml.com/download.html but I have tried the other snippets too but it doesn't even come to success.
Under Inspection tools, I see success request and blob data in response, but it takes about 10-15 seconds for the blob data to show under Network in browser
Please help. I have been at it all evening and can't seem to figure out undefined response.
For ajax download you should dynamic add link, trigger click and then delete.
var formData = new FormData();
//Fill formData with fields and files
console.log('Posting form from ajax');
$.ajax({
url: "/createPdf",
type: "POST",
data: formData,
contentType: false,
processData: false,
xhrFields: {
responseType: 'blob'
},
success: function (response, status, xhr) {
var a = document.createElement('a');
var url = window.URL.createObjectURL(response);
a.href = url;
a.download = 'myfile.pdf';
a.click();
window.URL.revokeObjectURL(url);
},
error: function (xhr, status, error)
{
var err = xhr.responseText;
alert(err);
}
You mentioned in your form.submit () it works without any issue. What type are you using, POST or GET? I World try to change it in your ajax request. I'm no java pro but maybe your Servlet only reacts to GET requests. When I worked with Ajax and Servlets I used http Servlet where I overwrote the doGet method.

formData object not working with jquery AJAX post?

lets jump right into the code :
var formData = new FormData();
formData.append('name', dogName);
formData.append('weight', dogWeight);
formData.append('activity', dogActivity);
formData.append('age', dogAge);
formData.append('file', document.getElementById("dogImg").files[0]);
console.log(formData);
Here I am appending some strings and one file object to the formData object in order to send all the information asynchronous to the server.
Right after that I have this jquery ajax request :
$.ajax({
type: "POST",
url: "/foodoo/index.php?method=insertNewDog",
data: JSON.stringify(formData),
processData: false, // tell jQuery not to process the data
contentType: "multipart/form-data; charset=utf-8",
success: function(response){
console.log(response);
},
error: function(){
}
});
So here I am trying to POST the info to the server, on the server php file I have a simple print_r of the POST so I see what gets through and what not.
Unfortunately my response in the console.log(data) is empty.
Also if you check the HEADER in the Network tab you get the following empty output:
Success function gets called (just for clarification)
When you're sending an ajax request via jQuery and you want to send FormData you don't need to use JSON.stringify on this FormData. Also when you're sending file the content type must be multipart/form-data including boundry - something like this multipart/form-data; boundary=----WebKitFormBoundary0BPm0koKA
So to send FormData including some file via jQuery ajax you need to:
Set data to the FormData without any modifications.
Set processData to false (Lets you prevent jQuery from automatically transforming the data into a query string).
Set the contentType to false (This is needed because otherwise jQuery will set it incorrectly).
Your request should look like this:
var formData = new FormData();
formData.append('name', dogName);
// ...
formData.append('file', document.getElementById("dogImg").files[0]);
$.ajax({
type: "POST",
url: "/foodoo/index.php?method=insertNewDog",
data: formData,
processData: false,
contentType: false,
success: function(response) {
console.log(response);
},
error: function(errResponse) {
console.log(errResponse);
}
});
if you did exactly as pervious anwswer and still not working
dont worry its working
maybe intelligence and quick wath are telling you its not working
but dont worry, look at network tap
its working
hope this saves your time
//For those who use plain javascript
var form = document.getElementById('registration-form'); //id of form
var formdata = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open('POST','form.php',true);
// xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
//if you have included the setRequestHeader remove that line as you need the
// multipart/form-data as content type.
xhr.onload = function(){
console.log(xhr.responseText);
}
xhr.send(formdata);

Does $.ajax automatically execute script, if the data returned is javascript?

I use a single JS file to post all my data back to my server, using:
$.ajax({
url: "/backend/post.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(response, status, xhr) // A function to be called if request succeeds
{
var ct = xhr.getResponseHeader("content-type") || "";
if(ct.indexOf("text/plain") > -1){
alert(response);
console.log('text - response');
}
if(ct.indexOf("text/javascript") > -1){
//eval(response);
console.log('javascript - response');
}
}
});
It goes through a whole load of functions on the server side but eventually gets to this one: output_javascript("alert('item added');");
function output_javascript($script)
{
header("content-type:text/javascript");
echo $script;
}
The idea was to have the $.ajax function display text or execute script from the server.
When $.ajax gets the response from output_javascript("alert('item added');"); then it executes the code twice. When I comment out the code to execute in the success function:
$.ajax({
url: "/backend/post.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(response, status, xhr) // A function to be called if request succeeds
{
}
});
Then it only executes the response once. Making me believe that $.ajax executes the code before returning the script in the response variable.
Is this true, or am I not understanding $.ajax correctly ? If I am misunderstanding the $.ajax function, could someone please tell me how to resolve this problem?
Yes, ajax will execute returned JavaScript code. We can see this in the documentation:
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:
So if you don't specify dataType, jQuery will figure it out from the response. Okay, but what does it do with a "script" value? Further down:
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
And later in the discussion:
If script is specified, $.ajax() will execute the JavaScript that is received from the server before passing it on to the success handler as a string.
All of this is easily found in the documentation by simply searching for the word "JavaScript" on the page.

415 Unsupported Media Type Using JQuery/FormData and Web Api

I'm getting a Error :
"POST {URL} 415 (Unsupported Media Type)" error
And cannot figure out why it's happening.
I'm trying to upload an excel file in JQuery using FormData.
Here is the code:
var formdata = new FormData();
var file = input.get(0).files[0];
formdata.append('content', file);
var url = "/Phrase/Import/" + $('.exportPanel #Language').val()
var ajax = $.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (data, textStatus, jqXHR) {
//Do something.
},
error: function (jqXHR, textStatus, errorThrown) {
//Do something.
}
});
Here is the controller code:
[Route("Import/{languageID}")]
[HttpPost]
public void ImportPhrases([FromUri]int languageID, [FromBody]Stream content)
{
_service.ImportPhrases(content, languageID);
}
I noticed that, according to Fiddler, the content type of the request is different to that of the response (not sure if this makes a difference?).
Request: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Response: application/json; charset=utf-8
The JQuery above is being used in a different part of the system, but uses WCF instead of Web API (am in the process of changing from WCF to MVC/Web API), again I'm not sure if this makes a difference?
Can anyone tell me what I'm doing wrong please?
Many thanks.
415 Unsupported Media Type
The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
contentType does matter - it tells the server what you are uploading. In this instance, you have set the value to false. The server cannot recognise this, so it returns false. If you do not need a specific content type, you should remove the contentType line to allow the jQuery default to kick in.

Categories