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);
Related
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.
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.
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
I have array of video files. i tried to upload. in below code console gives result empty object. How to select video file and upload. is it possible??
var pictureInput=['hp.mp4'];
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput[0]);
console.log(myFormData)
$.ajax({
url: 'uploadurl',
type: 'POST',
processData: false,
contentType: false,
dataType : 'json',
data: myFormData
});
For security reasons, it is not possible to read or upload files by name from a script. The user must either explicitly select the files from a dialog, or drag-and-drop them to the page. (If it were allowed, pages would be able to read and transmit any file on your system simply by knowing the name, which is not a good thing!)
You can find out more about how to let users specify files on the web here: https://developer.mozilla.org/en/docs/Using_files_from_web_applications
Use file object instead of file name only.
Previously i made successful this with Google App Engine (Java) and Angular 1.5
Look this accepted answer too. jQuery equivalent to XMLHttpRequest's upload?
var formData = new FormData();
formData.append('pictureFile',FILE_OBJECTS[0]);
$.ajax({
url: "YOUR_URL",
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
}).success(function(data) {
console.log("Success")
}).error(function(data) {
console.log("Error")
});
I'm trying to send compressed data to a server. To do this I'm attempting to pass it into jQuery's ajax function as a UInt8Array. I've based this on a related answer.
But it's not worked. When I look at the content through Wireshark, I see it's tried to do a .toString() on it, getting "[object Uint8Array]". There's very little other info on this around.
var dataCompressed = LZW.compressToByteArray(data);
$.ajax({
data: dataCompressed,
processData: false,
contentType: "application/octet-stream",
url: window.localStorage.getItem('servername') + '/Form/SaveData2?formId=' + results.rows.item(x).id,
headers: { 'Authorization': 'Basic ' + credentials },
type: "POST",
async: true,
success: function (data) {
}
});
You need to serialize the ArrayBuffer before jQuery tries to convert it for you. Some examples of how to do this can be seen here.
Try creating a Blob,
var blob = new Blob([dataCompressed], {type: "application/octet-stream"});
// ...
data: blob,
If jQuery is still handling this wrong, you could put this into a FormData
var fd = new FormData();
fd.append('post_field_name', blob, 'optional_file_name');
// ...
data: fd,
Doing it one of these ways is effectively "POSTing a File with AJAX"
I don't use jQuery so whilst I assume one of the above works I've not tested it. You may find that jQuery doesn't support posting data like this and have to move to a vanilla solution