jQuery upload file not work with ajax - javascript

I try to upload file with below simple code , but i get error:
$("#register_to_buy_card").submit(function (event) {
event.preventDefault();
var $this = $(this);
var url = $this.attr('action');
var form = document.forms.namedItem($this);
var formdata = new FormData(form);
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: formData,
success: function (data) {
},
error: function (data) {
}
});
});
I get this error:
TypeError: Argument 1 of FormData.constructor is not an object.
var formdata = new FormData(form);
HTML:
<form id="register_to_buy_card" enctype="multipart/form-data" accept-charset="UTF-8" action="http://localhost/sample/registerToBuyCard" method="POST">
<label for="passport">Passport Image</label>
<input type="file" name="passport">
<div class="checkbox">
<button class="btn btn-default" type="submit">Submit</button>
</form>

The error you are getting is because:
var form = document.forms.namedItem($this);
namedItem expects a string. You are passing it var $this = $(this);, which is a jQuery object.
this is already a form object. So change:
var $this = $(this);
var url = $this.attr('action');
var form = document.forms.namedItem($this);
var formdata = new FormData(form);
to
var formdata = new FormData(this);
(Yes, those four lines should be replaced with a single line).
Then see this other question which covers the issues not directly related to your error message.

The issue is the element passed in the FormData is not the form but a jQuery object. You need to put the form which is this in the context.
You need to update this:
var formdata = new FormData(this);
and use :
contentType:false,
processData:false,
in the ajax options.
Updated code should be:
$("#register_to_buy_card").submit(function (event) {
event.preventDefault();
var url = $(this).attr('action');
var formdata = new FormData(this); // <--------update with 'this'
$.ajax({
url: url,
type: "POST",
dataType: "json",
data: formData,
contentType:false, //<-----------required
processData:false, //<-----------required
success: function (data) {
},
error: function (data) {
}
});
});

Related

attach additional variable to ajax processing input type file

<input type='file' id='inpfile' accept='image/jpeg,image/png,image/gif' hidden>
I need to change src of imgauth but also need an aditional variable called name
$('#inpfile').change(function(){
var name = $('#selauth').val(); // this is the additional variable
var file_data = $('#inpfile').prop('files')[0];
var form_data = new FormData();
form_data.append('inpfile', file_data);
$.ajax({
url: "authors-pro-img-from-disc.php",
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data, // this works
//data: {form_data, 'name': name}, // this doesn't work
success: function(data){
$('#imgauth').attr('src', data);
}
});
});
php side
$name = $_POST['name'];
So how can I attach name variable and send it to server, together with image data.
You need to append name field the same way you did for the file:
var name = $('#selauth').val(); // this is the additional variable
var file_data = $('#inpfile').prop('files')[0];
var form_data = new FormData();
form_data.append('inpfile', file_data);
form_data.append('name', name); // <-------- append name
Then read in on the server as $_POST['name'].

Uploading xml file and image file together with same submit using one ajax call

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.

How to get FormData object and submit the form data by ajax use asp.net mvc

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);
}

What is wrong with this piece of code

This piece of code of a form submission is working perfectly in Google chrome meanwhile in Firefox it does not. Can somebody tell me what is wrong with my code?
$(document).ready(function(e){
/*sending post data to php script */
$("form[id='postForm']").submit(function(e){
e.preventDefault();
var text = $('#postText').val();
var formData = new FormData($(this)[0]);
formData.append('postText', text );
$.ajax({
url: "home.php?module=facebook&action=post-news&method=script",
type: "POST",
data: formData,
cache: false,
processData: false,
contentType: false,
context: this,
success: function (msg) {
window.location.reload();
}
});
e.preventDefault();
});
$('input:file').on('change', function () {
var formData = new FormData($(this)[0]);
//Append files infos
jQuery.each($(this)[0].files, function(i, file) {
formData.append('imageToPost[' + i + ']', file);
});
});
});
Quickly checked console:
TypeError: Argument 1 of FormData.constructor does not implement interface HTMLFormElement.
The problem is here:
$('input:file').on('change', function () {
var formData = new FormData($(this)[0]); <--- HERE
this is not a form, but input element. Not sure what you wanted to achieve here, but probably serialize your form. For this you need to do:
var form = $("#postForm")[0];
var formData = new FormData(form);
And then append your file.
Hope this helps.

How do I add additional POST parameters to ajax file upload?

I'm using ajax file upload javascript and php script to upload an image. It works satisfactorily with $_FILES but I need to send some additional data to the processing script. The form HTML looks like:
<form id="image1" action="" method="post" enctype="multipart/form-data">
<label>image 1?</label>
<p><input type="file" class="saveImage" name="image1" value="<?php echo $something; ?>" id="<?php echo $id; ?>" additional_info="some data" /></p>
<p> <input type="submit" value="Upload" class="submit" /></p>
</form>
I need to be able to pass a variable id and some other data, call it "additional_data" to the php script, then process it in my php script using $additional_data = $_POST['additional_data']. The javascript I'm using is:
<script>
$(document).ready(function (e) {
$("#image1").on('submit',(function(e) {
e.preventDefault();
$("#message").empty();
$('#loading').show();
var DATA=$(this).val();
var ID=$(this).attr('id');
var ADDL=$(this).attr('additional_data');
var dataString = 'image1='+DATA+'&id='+ID+'&additional_info='+ADDL;
$.ajax({
url: "uploadFile.php",
type: "POST",
// data: new FormData(this),
data: new FormData(this,dataString),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$('#loading').hide();
$("#message").html(data);
}
});
}));
});
</script>
It doesn't send the dataString, only the FILES array.
I also wanted to do the same thing.
Here's my solution :
The JS part :
var file_data = this.files[0];
file_data.name = idaviz +'.pdf';
var form_data = new FormData();
form_data.append("file", file_data);
form_data.append('extraParam','value231');
console.log(file_data);
console.log('here');
var oReq = new XMLHttpRequest();
oReq.open("POST", "ajax_page.php", true);
oReq.onload = function (oEvent) {
if (oReq.status === 200) {
console.log('upload succes',oReq.responseText);
} else {
console.log("Error " + oReq.status + " occurred when trying to upload your file.<br \/>");
}
};
oReq.send(form_data);
});
The PHP part:
echo $_REQUEST['extraParam']; //this will display "value231"
var_dump($_FILES['file']); //this will display the file object
Hope it helps.
Addition info about extra parameters on formData can be found
here!
I hope I understand you right. Maybe this snippet helps you:
var formData = new FormData();
formData.append("image1", fileInputElement.files[0]);
formData.append("ID", ID);
formData.append("ADDL", ADDL);
And then set this formData variable as data:
type: "POST",
data: formData,
contentType: false,

Categories

Resources