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
.
Send FormData and String Data Together Through JQuery AJAX
Use append
var img_data = new FormData($("form")[0]);
img_data.append('id', id);
send formData and other object from ajax to php
You have to append each element within the serialized form data into the formData
object.
Refer here: Send FormData and String Data Together Through JQuery AJAX?
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.
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');
How to send String data with formdata in ajax
To achieve this you can use the append()
method of FormData
to add whatever additional information you require:
$("#btnUpdate").click(function(e) {
e.preventDefault();
var $btn = $(this).attr('value', 'Please Wait...');
var formData = new FormData($("#frm_data")[0]);
formData.append('desc', CKEDITOR.instances.editor1.getData());
$.ajax({
url: 'update_job.php',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'post',
success: function(response) {
$btn.attr('value', 'Update');
}
});
});
Send form data (string) and array through AJAX jQuery form submit
jQuery:
$.ajax({
type: "POST",
url: "scripts/send-mail.php",
data: {
email: $('input[name="user-mail"]').val(),
basketData: basketData
}
success: function(data) {
console.log(data);
}
});
PHP:
$email = $_POST['email'];
$basketData = $_POST['basketData'];
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.
Uploading both data and files in one form using Ajax?
The problem I had was using the wrong jQuery identifier.
You can upload data and files with one form using ajax.
PHP + HTML
<?php
print_r($_POST);
print_r($_FILES);
?>
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
jQuery + Ajax
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
Short Version
$("form#data").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.post($(this).attr("action"), formData, function(data) {
alert(data);
});
});
Related Topics
Do Dom Tree Elements With Ids Become Global Properties
Why Calling Setstate Method Doesn't Mutate the State Immediately
In What Situations Would Ajax Long/Short Polling Be Preferred Over Html5 Websockets
Get Pixel Color from Canvas, on Mousemove
Detect Which Word Has Been Clicked on Within a Text
Jsfiddle Code Not Working in My Own Page
When Is Nodelist Live and When Is It Static
Disable Interpolation When Scaling a ≪Canvas≫
How to Modify the Url Without Reloading the Page
How to Change the Href Attribute For a Hyperlink Using Jquery
Convert Json Data to a HTML Table
Make Iframe Automatically Adjust Height According to the Contents Without Using Scrollbar
JavaScript Not Running on Jsfiddle.Net
How to Simulate a Hover With a Touch in Touch Enabled Browsers
How to Prevent Unicode Characters from Rendering as Emoji in HTML from JavaScript