How to use Formdata upload a file - javascript

I am using ajax to upload file cross domain. I think the bug is in js part.
But I can't figure it out what exactly wrong.
<form id="upload">
<div class="control-group">
<div class="controls">
<input id="file" name="file" type="file">
</div>
<div class="form-group">
<button class="btn btn-primary" onclick="Submit()" type="button">submit</button>
</div>
</div>
</form>
Here is my js
var form = $('#upload');
var formData = new FormData(form);
$.ajax({
url: URLs,
data: formData,
cache:false,
contentType: false,
processData: false,
crossDomain: true,
type:"POST",
dataType:'jsonp',
success: function(msg){
alert(msg["foo"]);
}
});

dataType:'jsonp',
JSONP is incompatible with POST requests (which file uploads require).
Use any other dataType supported by jQuery.
Since you are making a cross origin request, you will need the target server to grant you permission via CORS.

When the user clicks the button, you're calling the function Submit() but it isn't defined in your js. This should work:
function Submit()
{
var form = $('#upload');
var formData = new FormData(form);
$.ajax({
url: URLs,
data: formData,
cache:false,
contentType: false,
processData: false,
crossDomain: true,
type:"POST",
dataType:'jsonp',
success: function(msg){
alert(msg["foo"]);
}
});
}

Related

Jquery Serialize with File

Hi this code isn't working. Im using this serialize(); method but when I add an input type of file it isn't working. But if no file its working. Please help me.
$("#resimBtn").on("click", function(){
var dresim = $("#resimForm").serialize();
$.ajax({
url: "ayarlar/islem.php?islem=resim",
type: 'POST',
data: dresim ,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(cevap){
$("#resimAlert").html(cevap).hide().fadeIn(700);
}
});
});
<form id="resimForm" class="form-horizontal form-bordered" >
<div class="form-group">
<label class="col-md-3 control-label" for="inputDefault">Kategori Durum</label>
<div class="col-md-6">
<input type="file" name="resim">
</div>
</div>
<div class="col-md-6 col-md-offset-3">
<div id="resimBtn" class="btn btn-primary btn-lg pull-right">Ekle</div>
</div>
</form>
In the data key inside the Ajax call function, use a form data.
var form = $('#resimForm')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
data: formData,
Alternatively you can use a submit handler.
$('#resimForm').submit(function(e) {
e.preventDefault();
$.ajax({
//other Ajax stuff
data: new FormData(this),
});
});
USE this:
var formData = new FormData($('#resimForm')[0]);
$("#resimBtn").on("click", function(){
$.ajax({
url: "ayarlar/islem.php?islem=resim",
type: 'POST',
data: formData ,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(cevap){
$("#resimAlert").html(cevap).hide().fadeIn(700);
}
});
});

Uploading a file from a bootstrap modal using ajax

I am attempting to upload a file to a server from a bootstrap modal window, using ajax.
The modal html is
<div class="modal-body">
<div>
<form class="form" role="form" id="attachform" enctype="multipart/form-data">
<input type="file" name="file" id="file">
<button type="submit" class="btn btn-primary">Upload</button>
</form>
</div>
</div>
The Javascript
$("#attachform").on('submit',function(event){
event.preventDefault();
var postData = new FormData($("#attachform")[0]);
console.log(postData);
$.ajax({
url: "attachment.php",
type: "POST",
data: data,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});
The PHP server code
print_r($_POST);
print_r($_FILES);
I am not seeing anything in the $_FILES array when I run this.
Any suggestions?
Change the data value in your Ajax post to postData. postData contains the form data.
Change this section
data: data,
To
data: postData,//this contains the form data
You just need to change the data : data kew value inside the
$.ajax({
data : postData,
});
$.ajax({
url: "attachment.php",
type: "POST",
data: postData,
processData: false, // tell jQuery not to process the data
contentType: false
}).done(function(msg) {
console.log(msg);
$('#myAttachModal').modal('hide');
});
});
});

Uploading data and files in one form using Ajax PHP?

I'm using jQuery and Ajax for my forms to submit data and files but I'm not sure how to send both data and files in one form?
<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>
I was planning to use FormData as below
var formData = new FormData($(this)[0]);
but figured out that it does not work in IE<10 and which is not accepted. Is there any other approach for same?
This block should work for you.
$.ajax({
url: 'url',
type: 'POST',
async: true,
dataType: "json",
data: $('#data').serializeArray(),
error: function (a, b, c) { onError(a, b, c, parameters); },
success: function (data) { onSuccess(data, parameters); }
});
You can do like this in php instead of using form data,
Serialize you form data and send through ajax, like,
$.ajax({
type: 'post',
url: 'post.php',
data: $('#form').serialize(),
success: function () {
}
});
});
using $('#form').serialize() you can send your all form data to php.
I hope it helps,
function savedata(){
var vacancy_desc = CKEDITOR.instances['vacancy_desc'].getData();
var file_data = $('#fileupload').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('vacancy_records',vacancy_records);
form_data.append('vacancy_desc',vacancy_desc);
$.ajax({
url:pathname,
method:"POST",
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data:form_data,
cache:false,
success:function(datas){
alert('Updated successfully !');
return false;
}
});
}

Spring Boot and jQuery file upload : Unsupported media type

I am trying to upload a csv file with spring boot 1.2.0 REST controller and jQuery ajax. When I send the post request, I keep getting 415:Unsupported Media type error. Here is my form:
<form id="upload_form">
<div id="message">
</div>
<br/>
<div class="row" id="upload-file-div" style="display: none">
<div class='col-sm-3'>
<label>Select File</label>
<input type="file" name="file">
</div>
<div class='col-sm-3'>
<input type="button" id="file-upload" class="btn btn-primary" value="Upload" onclick="uploadFile()"/>
</div>
</div>
</form>
Here is my method to upload file:
function uploadFile(){
var response = api.uploadCSV($("#upload_form"));
if(response.status === 'OK'){
$("#message").css('color', 'green');
}else{
$("#message").css('color', 'red');
}
$("#message").html(response.message);
}
Here is the actual jQuery POST:
upload: function (url, form, ignoreSuccess) {
var response = null;
if (!this.validate(form)) {
var array = form.serializeArray();
alert(array);
var formData = new FormData(form);
console.warn(formData);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
cache: false,
contentType: false,
processData: false,
async: false,
beforeSend: function (request) {
if (api.getSession() !== null) {
request.setRequestHeader("Authorization", "Bearer " + api.getSession().bearer);
}
},
success: function () {}
}).done(function (msg) {
response = msg;
});
}
return response;
}
Following is my controller:
#RequestMapping(consumes = "multipart/form-data", method = RequestMethod.POST,
value = "/upload/twitter", produces = MediaType.APPLICATION_JSON_VALUE)
public Response<String> uploadCsv(CsvUploadModel form) {
//Code
}
I have both MultipartConfigElement and MultipartResolver annotated in my spring boot class. I am using spring boot 1.2.0. When I send the post request with PostMan (chrome extension), it works as expected. However, when I try the above jquery code, it keeps throwing unsupported media type error.
Following things I have tried:
Playing around content-type header, finally I have set the contentType to false.
Using form.serializeArray(), iterating over it and appending individual elements into formData.
Sending the form object instead of form data.
Can anyone please help me with this? Thanks in advance.
You can append your file input in your formData; the following changes needs to be made:
This:
<input type="file" name="file">
Should be:
<input type="file" name="file" id="file">
And in your ajax code, this:
var formData = new FormData(form);
console.warn(formData);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
Should be:
var formData = new FormData();
formData.add("file",$('#file')[0].files)
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,
Or:
var formData = new FormData(form[0]);
$.ajax({
type: "POST",
url: API_PROXY + url,
data: formData,

AJAX formdata POST submit working in IE9/Chrome but not in Firefox

I have some AJAX script that submits a form and then updates the web page.
My Code:
HTML:
<form action='jobs.php' method='post' name='editUpdate' enctype='multipart/form-data' id="form-add">
<hr />
<textarea name='description' id="title" class="text1" placeholder="Add Update" cols='100' rows='5'></textarea>
<input type="submit" name='action' id="submit" value="Save Update"></input>
</form>
AJAX:
<script>
$('#form-add').submit(function(e){
var formObj = $(this);
var formURL = formObj.attr("action");
var formData = new FormData(this);
var prependbdDiv = $('#prependbody');
$.ajax({
url: formURL,
type: 'POST',
data: formData,
dataType: "json",
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(response) {
if(response.success == "1"){
prependbdDiv.prepend("<tr><td>"+response.datetime+"</td><td>"+response.updatedesc+"</td></tr>");
$('#title').val('');
$("#form-add").fadeToggle();
}
},
error: function(response)
{
alert("ERROR");
},
});
e.preventDefault();
});
</script>
This seems to have resolved my issue:
Submiting a form with Ajax by using FormData on Firefox and IE10+
I am curious why this is the case or is it bad programming on my behalf?
Also when using FireBug the post data does not appear similar to that of the post data from a standard HTML form. IE, with the ajax post using formdata FireBug lists no "Parts" section under the POST details.
Thanks for your help!

Categories

Resources