I'm using javascript's 'formData' to send image files with ajax. How can I attach other data to formData, for example a text string?
JS:
$("#post-image").click(function(){
$.ajax({
url: "../../build/ajaxes/upload-photo.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
}
});
});
PHP:
In my PHP I can access the image by using $_FILES["images"]
. I don't know what to use for my additional data passed with formdata.
I'm using javascript's 'formData' to send image files with ajax. How can I attach other data to formData, for example a text string?
JS:
$("#post-image").click(function(){
$.ajax({
url: "../../build/ajaxes/upload-photo.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
}
});
});
PHP:
In my PHP I can access the image by using $_FILES["images"]
. I don't know what to use for my additional data passed with formdata.
3 Answers
Reset to default 3If you want to add parameters to FormData use FormData.append
$("#post-image").click(function(){
formdata.append('name', 'value');
$.ajax({
url: "../../build/ajaxes/upload-photo.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (response) {
console.log(response);
}
});
});
In PHP use $_POST["name"]
to get the value.
You need to submit the form as multipart. Here's a SO solution to your question: Making an HTTP POST call with multipart/form-data using jQuery?
Not an exact duplicate, so I didn't mark it as such, but it's a direct reference to the solution to your problem.
Edit: you'll notice that some of the answers reference FormData as a solution as well. Once you get the data posting properly, you can then access it with the normal $_FORM collection in PHP.
If you have Big form with Multiple file uploads then not use MALSUP JQUERY PLUGIN .It will send all your form fields with just
$(form).ajaxSubmit();