This question already has answers here:
How to use FormData for AJAX file upload?
(9 answers)
Closed 7 years ago.
This works when submitting the form directly. Perhaps I am not passing my "form" object to FormData correctly. Laravel is saying that "file" isn't being passed and when I console.log(formData), I'm seeing an object containing the proto prop but as far as I can tell none of my fields
HTML
<form enctype="multipart/form-data" accept-charset="utf-8" method="POST" action="/file">
<input id="file" type="file" name="file">
<button type="submit">Upload</button>
</form>
JS
$('.file-upload-form').submit(function (e) {
e.preventDefault();
submitUploadFileForm($(this)); //also tried just passing this without wrapper
});
function submitUploadFileForm(form){
console.log(form);
var formData = new FormData(form); //Needed for passing file
console.log(formData);
$.ajax({
type: 'post',
url: '/file',
data: formData,
success: function () {
alert('done');
},
processData: false,
contentType: false
});
}
FormData accepts a form DOMElement, not a jQuery object. You need to call submitUploadFileForm() just passing the this reference to the form:
submitUploadFileForm(this);
Related
This question already has answers here:
jQuery AJAX file upload PHP
(5 answers)
Closed 3 years ago.
Well, I have tried a lot of JS codes to post one form with multiple data [2 Files & 1 textarea] and they didn't work well.
But How to send non-empty form data to PHP using AJAX?
<form method="post" enctype="multipart/form-data">
<textarea id="acas"></textarea>
<input id="uimage" type="file" name="image" accept=".png,.jpg,.gif"/>
<input id="uaudio" type="file" name="audio" accept=".mp3"/>
<input id="armes" style="display: none;" name="send" type="submit"/>
</form>
By default I use this JS code below to submit form, But it reloads page:
$("#acas").on('keydown', function(e) {
if (e.key == "Enter") {
if (e.shiftKey) {
} else {
e.preventDefault();
$("#armes").click();
}
}
});
Use this code
$(document).on('submit', 'form', function (e)
{
var form = new FormData(this);
jQuery.ajax({
url: "",
method: 'POST',
processData: false,
contentType: false,
dataType: "json",
data: form,
success: function (response)
{
}
});
return false;
});
I want to send uploaded image and uploaded XML to PHP file using one ajax. I used two form data, Is this the correct way to do it.
<input type="file" class="form-control-file" name="fileToUpload" id="uploadFile"/>
<input type="file" name="imageToUpload" id="uploadImg"/>
<input type="submit" id="upload_xml" name="transcriptform" value="Upload File" class="btn btn-info">
Ajax call:
$('#upload_xml').on('click', function() {
var file_data = $('#uploadFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
var img_data = $('#uploadImg').prop(files('files')[0];
var img_form = new FormData();
img_form.append('img', img_data);
$.ajax({
url: "get_old_contents.php",
//dataType: 'script',
//cache: false,
contentType: false,
processData: false,
data: form_data,img_form; //is this correct
type: 'post',
complete: function(response){
$('#res').html('Your files are uploaded successfully!');
}
});
});
Not quite. You need to send a single FormData object in the data property of the $.ajax call. To do that you can use append() to add both files together, like this:
$('#yourForm').on('submit', function(e) {
e.preventDefault();
var form_data = new FormData();
var file_data = $('#uploadFile').prop('files')[0];
var img_data = $('#uploadImg').prop('files')[0];
form_data.append('file', file_data);
form_data.append('img', img_data);
$.ajax({
// ...
data: form_data,
});
});
You can also simplify this if you can change the name attribute of the file inputs, by providing a reference to the <form> element to the constructor of the FormData object:
<input type="file" class="form-control-file" name="file" id="uploadFile"/>
<input type="file" name="img" id="uploadImg"/>
$('#yourForm').on('submit', function(e) {
e.preventDefault();
var form_data = new FormData(this);
$.ajax({
// ...
data: form_data,
});
});
Note that in both cases you should be hooking to the submit event of the form element, not click of the button, and using preventDefault() on the event argument of the handler to stop the standard form submission.
I would like to get a form object and submit the data to server with a button click in Asp.net MVC.
This is my HTML code:
<form method="post" form-sync="ajax">
#Html.Hidden("InvtId", item.InvtId)
</form>
This is my JS code:
$(document).on("click", "[form-sync='ajax']", function() {
var formdata = new FormData($(this).closest("form")),
url = $(this).data("url");
$.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(response) {
alert(response.message);
return false;
},
});
});
This is my MVC code:
var data = Request["InvtId"];
The problem is the data variable is empty
Any help would be greatly appreciated, thanks.
Your form-sync attribute is non standard so your HTML is invalid. You should make that a data attribute.
You need to hook to the submit event of the form, not click.
The FormData constructor expects a DOMElement, not a jQuery object as you are currently passing to it. You can just give the this reference as that is the DOMElement.
The form has no data-url attribute. I assume you want the action property instead, which will default to the current page as you haven't provided one explicitly.
The return statement in your success handler is redundant.
You need to stop the standard form submission (as you're submitting via AJAX instead) by calling preventDefault() on the passed submit event.
Here's a complete example with all the above fixes:
<form method="post" data-form-sync="ajax">
#Html.Hidden("InvtId", item.InvtId)
</form>
$(document).on('submit', '[data-form-sync="ajax"]', function(e) {
e.preventDefault();
$.ajax({
url: this.action,
type: 'post',
data: new FormData(this),
processData: false,
contentType: false,
success: function (result) {
alert(result.message);
},
});
})
The problem is that you are passing in a jQuery element and NOT a DOM element.
For the FormData to actually return what you expect, you need to pass in a DOM element to its constructor.
Here, try this instead:
var formdata = new FormData($(this).closest("form")[0]);
Another problem is that the form has no data-url attribute.
Use the action property instead, it will return the url of the current page if you have not given a url yourself.
Here, use this instead:
var url = this.action; // or $(this).prop('action');
HTML
< button type="button" class="btn btn-primary"
onclick="saveData()">Save</button>
JS Code
Inside of function saveData()
var formData = new FormData();
get values with serializeArray
var formulario = $("#miFormulario").serializeArray();
if there are extra data or files
formulario.push({ "name": fileName, "value": file });
add information to formData
formulario.forEach((d) => {
formData.append(d.name, d.value); });
ajax request
$.ajax({
timeout: 0,
url: "/InfoController/savingInfo",
method: "post",
data: formData,
contentType: false,
processData: false,
success: function (result) { //do something }
});
Controller
[HttpPost] public JsonResult savingInfo() {
if (Request.Files.Count > 0)
{ ... }
var data = Request.Form;
var valor1 = data["dato1"];
return Json(true);
}
This question already has answers here:
Is it possible to use Ajax to do file upload?
(7 answers)
Closed 7 years ago.
Is it possible to pass file from JavaScript to PHP? (Best using ajax).If we have following code:
<!DOCTYPE html>
<html>
<body>
<input type='file' id='upld' onChange=' f=this.files[0] '>
<input type='button' onClick='ajax_pass()'>
<script>
function ajax_pass()
{
console.log(f);
//Send 'f' using ajax to php imaginary file...
}
</script>
</body>
</html>
I'm new to JS programming and can't imagine how POST or GET can contain whole image.Can you clarify it to me please?
HTML Code
<input id="myfile" type="file" name="myfile" />
<button id="upload" value="Upload" />
Jquery Code
$(document).on("click", "#upload", function() {
var file_data = $("#myfile").prop("files")[0]; // Getting the properties of file from file field
var form_data = new FormData(); // Creating object of FormData class
form_data.append("file", file_data) // Appending parameter named file with properties of file_field to form_data
form_data.append("user_id", 123) // Adding extra parameters to form_data
$.ajax({
url: "/upload_file.php",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post'
});
});
Php Code
print_r($_FILES);
print_r($_POST);
So, I have the following form and js/php:
php
<form enctype="multipart/form-data">
<input id="fileupload" type="file" name="files[]" class="files " onChange="UploadImage" accept='image/*'/>
<input type="button" class="submit_form" value="submit">
</form>
<?php
add_action( 'wp_ajax_UploadImage', 'UploadImage' );
function UploadImage()
{
$upload_dir = wp_upload_dir();
$files = $_FILES['files'];
//Some function
}
?>
JS
function UploadImage(e)
{
jQuery('#fileupload').fileupload({
url: upload_image.ajax_url,
});
if(jQuery('#fileupload')) {
var form = document.forms.namedItem("upload_video");
var formdata = new FormData(form);
formdata.append('action', 'UploadImage');
jQuery.ajax({
success : function(data){
alert('sddsf');
}
})
}
};
As you can see from here, when an image is selected using Blueimp jQuery File upload (which the js is not properly written), I want the image file to be handled by the php function.
In other words, the js is not correctly written and I am not sure how to initiate the plugin then when the image is selected, it is processed by the php function via ajax (meaning, how do I parse the file info to php function via ajax?)
Don't use $.ajax directly. The plugin already does that behind the scenes.
Here's a working example, based on your code, but adapted to run on JSFiddle:
$(document).ready(function(){
var url = '/echo/json/';
var formdata = {json: JSON.stringify({field1: 'value1'})};
jQuery('#fileupload').fileupload({
url: url,
formData : formdata,
dataType: 'json',
type: "POST",
contentType:false,
processData:false,
success : function(data){
alert('success...');
console.dir(data);
}
});
});
Demo: http://jsfiddle.net/pottersky/8usb1sn3/3/