Submitting a form with a file using JQuery and AJAX - javascript

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

Related

How to send both array and file via same AJAX request?

I am trying to send both an image file and a array via my AJAX request to my PHP script, but either the array or the image file dosen't show up. I have located the problem being the lines, that you have to add to your AJAX when you are dealing with files.
contentType: false,
processData: false,
If these two lines are added the array arrives at PHP script empty. What can I do differently? :)
My AJAX:
$('#createMember').on('submit', function(event){
event.preventDefault();
$("#LoadingIcon").show();
var form_data = $(this).serialize();
$.ajax({
url:"scripts/createMember.php",
method:"POST",
data:form_data,
cache: false,
contentType: false,
processData: false,
success:function(data)
{
$.notify({
title: '<strong>Created!</strong><br>',
message: 'Member is now created!'
});
$("#LoadingIcon").fadeOut(200);
});
});
My HTML
<form method="post" id="opretMedlem" enctype="multipart/form-data">
<input type="text" name="info[name]" class="form-control1 info" />
<input type="text" name="info[age]" class="form-control1 info" />
<input type="file" name="info[image]" class="form-control1 info" />
<input type="submit" name="submit" class="btn btn-info" value="Create member" />
</form>
You have forgot to use enctype in ajax request. Also try to use FormData() constructor instead of serializing the data.
$('#opretMedlem').on('submit', function(event){
event.preventDefault();
var form_data = $(this).serialize();
var form = $(this)[0];
var data = new FormData(form);
$.ajax({
url:"scripts/createMember.php",
enctype: 'multipart/form-data',
method:"POST",
data:data,
cache: false,
contentType: false,
processData: false,
success:function(data) {
alert('done');
}
});
});
Look at the fiddle: https://jsfiddle.net/up8zavtb/

Sending files and other data using ajax

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

how to reuse a form and jquery ajax call in multiple sections of a document?

I am working on jquery dialog email attachment. I created a separate form to upload file that uses formdata object. I want to reuse the form and its related ajax call in different dialogs in the same php page(reason: need email attachment functionality in other dialogs). How can i achieve this?
Jquery Ajax call:
$('#attchform').submit(function(event) {
$.ajax({
url: 'uploadfile.php',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
document.getElementById("fileToUpload").disabled = true;
$("#loadimg").html(data);
}
});
event.preventDefault();
});
Html form:
<form id="attchform" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Attach" name="submit">
</form>
<div id="loadimg"></div>
You can define a function and call any where in the same page:
function UploadFile(){
$.ajax({
url: 'uploadfile.php',
type: 'POST',
data: new FormData(this),
processData: false,
contentType: false,
success: function(data) {
document.getElementById("fileToUpload").disabled = true;
$("#loadimg").html(data);
}
});
}
$('#attchform').submit(function(event) {
UploadFile();
event.preventDefault();
});

Javascript: Upload some files synchronous from a form

I need to upload multiple files from a form. I have an event "submit" that processes the data of the form, uploads the files and then shows a message. I need that this process syncronous to show the message when the files have been uploaded.
I have this HTML code in the form:
<form method="post" action="files/upload_project_file" id="upload_project_file_form" target="upload_project_file_iframe" enctype="multipart/form-data">
<input type="file" name="uploaded_file[]" class="multi" maxlength="0" accept="" />
<input type="hidden" name="action" value="upload_project_file">
<input type="hidden" name="id_project_files" value="" id="id_project_files">
</form>
And this Javascript code in the javascript Submit event:
//processes data
//...
//Upload files
var data = new FormData();
jQuery.each($('input[name^="uploaded_file"]')[0].files, function(i, file) {
data.append('uploaded_file'+i, file);
});
data.append('id_project_files', $("#id_project_files").val());
$.ajax({
url: 'files/upload_project_file',
enctype: 'multipart/form-data',
data: data,
cache: false,
contentType: false,
processData: false,
async: false,
type: 'POST',
success: function(data){
//Clear
$('.filesToUpload').empty();
}
});
//Then show the message and redirect page
//...
I upload only one file but not all, I can't, I don't know why. I've seen Jquery.each runs only once.
No, thanks "user2698878", I didn't want to use Uploadify.
Finally I changed the ajax code and it works perfectly. This is the new code:
var formData1 = new FormData($("#upload_project_file_form")[0]);
$.ajax({
url: "files/upload_project_file",
enctype: 'multipart/form-data',
type: 'POST',
data: formData1,
async: false,
success: function (data) {
$('.filesToUpload').empty();
},
cache: false,
contentType: false,
processData: false
});

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