How to send FormData objects with Ajax-requests in jQuery?
I believe you could do it like this :
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Notes:
Setting
processData
tofalse
lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.Setting the
contentType
tofalse
is imperative, since otherwise jQuery will set it incorrectly.
Ajax post FormData and the form
Try passing this
to FormData
Also, you were setting type
twice.
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData(this);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
Send FormData object AND an additional parameter via ajax
Try:
var formData = new FormData();
formData.append('file', this.files[0]);
formData.append('CustomerId', 2);
/*
note:: appending in form Data will give "csrf token mismatch error".
so better you make a input feild of type hidden with name = CustomerId
and value = 2
*/
$.ajax({
url: urlUploadProductsFile,
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false
}, 'json');
Sending multipart/formdata with jQuery.ajax
Starting with Safari 5/Firefox 4, it’s easiest to use the FormData
class:
var data = new FormData();
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have a FormData
object, ready to be sent along with the XMLHttpRequest.
jQuery.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
});
It’s imperative that you set the contentType
option to false
, forcing jQuery not to add a Content-Type
header for you, otherwise, the boundary string will be missing from it.
Also, you must leave the processData
flag set to false, otherwise, jQuery will try to convert your FormData
into a string, which will fail.
You may now retrieve the file in PHP using:
$_FILES['file-0']
(There is only one file, file-0
, unless you specified the multiple
attribute on your file input, in which case, the numbers will increment with each file.)
Using the FormData emulation for older browsers
var opts = {
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
};
if(data.fake) {
// Make sure no text encoding stuff is done by xhr
opts.xhr = function() { var xhr = jQuery.ajaxSettings.xhr(); xhr.send = xhr.sendAsBinary; return xhr; }
opts.contentType = "multipart/form-data; boundary="+data.boundary;
opts.data = data.toString();
}
jQuery.ajax(opts);
Create FormData from an existing form
Instead of manually iterating the files, the FormData object can also be created with the contents of an existing form object:
var data = new FormData(jQuery('form')[0]);
Use a PHP native array instead of a counter
Just name your file elements the same and end the name in brackets:
jQuery.each(jQuery('#file')[0].files, function(i, file) {
data.append('file[]', file);
});
$_FILES['file']
will then be an array containing the file upload fields for every file uploaded. I actually recommend this over my initial solution as it’s simpler to iterate over.
Send form data with jquery ajax json
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
formData object not working with jquery AJAX post?
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
tofalse
(Lets you prevent jQuery from automatically transforming the data into a query string). - Set the
contentType
tofalse
(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);
}
});
Using FormData object in jQuery ajax request makes page redirect
The form data still find its way to the server but now the page redirects to the page in the url. I cannot figure out why at all.
In the first handler you are using:
form.submit((event) => {
This is the .submit() method to handle the
.on( "submit", handler )
In your second fragment, instead you are using:
form.onsubmit((event) => {
The onsubmit is not a jQuery method hence your problem.
A second issue is related to this line:
let formData = new FormData(this);
Change it to:
let formData = new FormData(event.target);
The this keyword in your function context is not the current form but the default window object.
Send FormData and String Data Together Through JQuery AJAX?
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
Added a for
loop and changed .serialize()
to .serializeArray()
for object reference in a .each()
to append to the FormData
.
Related Topics
Can Scripts Be Inserted With Innerhtml
Creating a Textarea With Auto-Resize
How to Render HTML String as Real Html
Passing Variable Through JavaScript from One HTML Page to Another Page
Can You Style an HTML Radio Button to Look Like a Checkbox
"Uncaught Typeerror: Illegal Invocation" in Chrome
Retrieving the Text of the Selected ≪Option≫ in ≪Select≫ Element
Console.Log of Element.Children Shows 0 Length But Has Three Entries When Expanded Later
How to Check File Mime Type With JavaScript Before Upload
Make Iframe Automatically Adjust Height According to the Contents Without Using Scrollbar
Trigger Event When User Scroll to Specific Element - With Jquery
How to Stop a Web Page from Scrolling to the Top When a Link Is Clicked That Triggers JavaScript