Sending files and other data using ajax - javascript

I am trying to send data to server which includes files and strings with ajax. My code in jsp is:
<html>
...
<body>
...
<form id="data" method="post" enctype="multipart/form-data">
<input name="classroomID" type="hidden" value="1" />
<input type="file" name="file" size="30" id="file" />
<button>Submit</button>
</form>
<script type="text/javascript"
src='https://code.jquery.com/jquery-3.1.0.min.js'></script>
<script type="text/javascript" src='sendUpload.js'></script>
...
</body>
</html>
And my sendUpload.js looks like this:
$(document).ready(function() {
console.log("here");
$("form#data").submit(function(ev){
ev.preventDefault();
console.log("Submitted");
var formData = new FormData($(this)[0]);
console.log(JSON.stringify(formData));
$.ajax({
url: "UploadServlet",
type: 'POST',
data: formData,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
But the JSON data is empty. any suggestions? I am using java servlet.

What kind of errors are you getting? Looks like your jquery selector is wrong, i'd try changing this:
$("form#data").submit(function(ev){
To this:
$("#data").submit(function(ev){
Not really sure though, you should post the specific errors.

$(document).ready(function() {
$("form#data").submit(function(e){
e.preventDefault();
$.ajax({
url: "UploadServlet",
type: 'POST',
data: {
classroomID: $('input[name="classroomID"]').val(),
file: $('input[name="file"]').val()
},
success: function (data) {
alert(data);
},
cache: false,
contentType: false,
processData: false
});
return false;
});
});
Does it work for you?

You can do this:
var formData = new FormData();
formData.append('classroomID', $('#classroomID').val());
formData.append('file', $('#file')[0].files[0]);
...and give your classroomID input field an id of 'classroomID'.
Also, you cannot inspect formData directly from the console so you will have to use this to debug:
for (var item of formData) {
console.log(item);
}

Related

Send file to api using Ajax

Im trying to send file to api using ajax , but form-data always null in both cases mentioned below
<form id="myformdoc">
<input type="file" size="45" name="file" id="file">
</form>
<script>
$('#file').on("change", function () {
// var formdata = new FormData($('form').get(0));
let myForm = document.getElementById('myformdoc');
let formData = new FormData(myForm);
$.ajax({
url: url,
type: 'POST',
data: formdata ,
cache: false,
processData: false,
contentType: false,
success: function (color) {
;
},
error: function () {
alert('Error occured');
}
});
});
</script>
Any idea why form-data always null ?
Try adding multipart/form-data in contentType parameter.
You need to use
formData append to add files to your formData function.
Change your jQuery code to this below and it will work fine and you can get the files on your backend to save them.
If you have other inputs in your form you can append them as well if you like to.
formData.append('file', $(this)[0].files[0])
Demo:
$('#file').on("change", function() {
//Initialize formData
let formData = new FormData();
console.log($(this)[0].files)
formData.append('file', $(this)[0].files[0]) //append files to file formData
$.ajax({
url: 'url',
type: 'POST',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(color) {
console.log(color);
},
error: function() {
alert('Error occured');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form enctype="multipart/form-data">
<input type="file" size="45" name="file" id="file">
</form>

How to send the <input type="file"> data from AJAX by putting it in object?

I have a simple upload file in my html like so:
<div class="col-md-12">
<span id="fileUploadErr">Please Upload A File!</span>
<div style="margin-bottom: 10px;"></div>
<input id="pickUpFileAttachment" type="file" name="attachFileObj" size="60" />
</div>
When I click on the "Submit" button the following action occurs:
$("form").submit(function() {
event.preventDefault();
var assignmentObj1 = {
selectionId: trDataSecondTable.selectionId,
inout: "in",
letterReceivedBy: $("#letterReceivedBy").val(),
letterIssuedSubBy: $("#letterIssuedSubBy").val(),
representativeNameEng: $("#representativeNameEng").val(),
letterId: 2,
assessmentNo: 0
imageFile: $("#representativeNameEng").val()
imageTitle:
}
console.log(jsonData);
$.ajax({
url: A_PAGE_CONTEXT_PATH + "/form/api/saveProcessAnexTwo",
method: "post",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(assignmentObj1),
success: function(response) {
},
error: function(response) {
switch (response.status) {
case 409:
alert("error");
}
}
});
});
I need to assign the fileName and the uploaded file while sending from AJAX and need to put it inside the assignmentObj1 variable so I tried: imageFile: $("#representativeNameEng").val() to get the file information but it is not coming. How can I get the file information and send from AJAX by putting it in a local variable? And also how can I get the name of the file which can be placed in the imageTitle: property?
This is how to deal with the file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jquery Ajax File Upload</title>
</head>
<body>
<div class="col-md-12">
<span id="fileUploadErr">Please Upload A File!</span>
<div style="margin-bottom: 10px;"></div>
<input id="pickUpFileAttachment" type="file" name="pickUpFileAttachment" size="60" />
</div>
<div class="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// $("form").submit(function(){
$('#pickUpFileAttachment').change(function(e){
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url : window.location.pathname + "/form/api/saveProcessAnexTwo",
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false,
success: function(response){
alert("suc");
$('.result').html(response.html)
} , error: function(response){
switch(response.status){
case 409:
alert("error");
}}
});
});
//});
});
</script>
</body>
</html>
Easiest method is to use formData to send data:
var data = new FormData();
$.each($('#filecontainer')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have formData object
$.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);
}
});
Hope this helps.

Submit an ajax-created form via ajax

I'm having trouble getting an ajax-loaded form (#ajaxLoadedForm) to submit via ajax. The formData object gathers no data. I figure I've got to attach an event-handler to the form so the DOM recognizes it, but I can't figure out how.
A couple of notes: I'm bypassing the 'submit' method and using a button (#button), so I can't attach the handler to that. The form itself is a sibling to #button, not a child.
<form id="ajaxLoadedForm" enctype="multipart/form-data" action="destination.php" method="POST">
<input type="hidden" name="state" value="1" />
<label for="fullname">Your Full Name</label>
<input type="text" id="name" autocapitalize="off" autocorrect="off" name="fullname" placeholder="your name" value="" />
</form>
<div id="button">Submit me!</div>
$('#button').click(function(){
var uploadData = new FormData($("#ajaxLoadedForm")[0]);
jQuery.ajax({
url: 'destination.php',
data: uploadData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
data = JSON.parse(data);
if (data['pass'] == false) {
console.log('fail');
} else {
console.log('success');
}
}
});
});
Try using the submit handler on the form itself
$('#ajaxLoadedForm').submit(function(e){
e.preventDefault();
var uploadData = new FormData(this);
});
Then make your button for submit a submit type
<button type='submit'>Submit</button>
In your php side, test the data coming by doing this:
print_r($_POST);
you can use serialize function for sending form data . Like below
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script >
$('#button').click(function(){
var uploadData = $('#ajaxLoadedForm').serialize();
jQuery.ajax({
url: 'destination.php',
data: uploadData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
data = JSON.parse(data);
if (data['pass'] == false) {
console.log('fail');
} else {
console.log('success');
}
}
});
});
</script>
Try below code..
$('#button').click(function(){
var uploadData = new FormData();
uploadData.append('fullName',$('#fullName').val());
jQuery.ajax({
url: 'destination.php',
data: uploadData,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
}
});
});
And try to access full name in php

Submitting a form with a file using JQuery and AJAX

I have a form, with a file input, that submits just fine when I use the default action to submit the form. But, when I use JQuery and AJAX to make the call to the PHP file, it does not seem to get the file. Is there something that I need to add for sending files through JQUERY/AJAX?
My HTML:
<form id="photo-form" enctype="multipart/form-data" method="post" action="">
<input type="hidden" name="MAX_FILE_SIZE" value="5000000"/>
<input type="file" class="upload-input" name="upload-new-input" autocomplete="off"/>
<input type="submit" name="submit" value="submit/>
</form>
My JQuery:
$(document).ready(function() {
$("#photo-form").submit(function(e) {
e.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
url: "uploadcover.php",
data: dataString,
async: false,
success: function(data) {
alert(data);
}
});
});
});
You can use FormData to upload file with data
Here is sample code
JQuery
$("#photo-form").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "uploadcover.php",
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(data) {
alert(data);
}
});
return false;
})
You can get it on PHP
PHP CODE
$Img = $_FILES['upload-new-input'];
You can see tutorial Uploading files with jquery ajax
Hope It helps you :)
You cannot access file directly.
You can use a plugin, to do this for you, i.e. https://github.com/blueimp/jQuery-File-Upload
Also, in html5 it is possible to access a file from file input as a blob. You can than send it using formData.
More info here: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

File upload using Jquery ajax without form

Here is mycode
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
var startdate=$("#from_date"+elem).val();
var enddate=$("#to_date"+elem).val();
$.ajax({
url: "addpackage/",
type:"post",
contentType:false,
data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
success: function(data) {
}
});
}
I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object]. How to post image with input field without form in jquery ajax?
You can do it like following. Hope this will help you.
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('startdate', $("#from_date"+elem).val());
dataimg.append('enddate', $("#to_date"+elem).val());
dataimg.append('packageid', elem);
dataimg.append('img', $("#browseimg"+elem)[0].files[0]);
$.ajax({
url: "addpackage/",
type:"post",
cache : false,
contentType : false,
processType : false,
data: dataimg,
success: function(data) {
}
});
}
You can try this:
Your JS Code:
<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
type: "POST",
url: url,
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
</script>
Dummy HTML:
<form method="post" action="addpackage/" id="yourFormID">
<input type="text" name="firstvalue" value="some value">
<input type="text" name="secondvalue" value="some value">
<input type="file" name="imagevalue">
</form>
in addpackage php file:
print_r($_POST);
print_r($_FILES);

Categories