How do file upload for Ajax - javascript

I'm trying to submit a form via ajax which has some images The following code returns an object (in console.form), "FormData", however how do I use it and or retrieve it, and whether it is right.
$("#form_galeria").unbind('submit').bind('submit', function(e) {
e.preventDefault();
var url = 'salvarGaleria.do';
var form;
form = new FormData();
form.append('fileUpload', e.target.files);
console.log(form);
$.ajax({
type: "POST",
url: url,
data: $("#form_galeria").serialize(),
processData: false,
contentType: false,
success: function(result) {
console.log(result);
},
error: function(err) {
console.log(err.status + ' - ' + err.statusText);
}
});
$('#multiplas').modal('hide');
return false;
});

Set the ajax data option to your FormData object. You will need to add whatever field values to the FormData object as well if you wish to send those along with the file upload. Also you have to append each indvidual file you cannot just append the e.target.files collection
for(var i=0; i<e.target.files.length; i++){
form.append("fileUpload[]",e.target.files[i]);
}
//or if you are only doing a single file
//form.append("fileUpload",e.target.files[0]);
form.append("someField",jQuery("#someField").val());
form.append("someOtherField",jQuery("#someOtherField").val());
$.ajax({
type: "POST",
url: url,
data: form,
processData: false,
contentType: false,
success: function(result){
console.log(result);
},
error: function(err){
console.log(err.status + ' - ' + err.statusText);
}
});

Related

I don't know why but my ajax POST method is not returning any response

This is my code , When I click on submit , somehow the data is inserting but that echo data in back php form is not showing in this front ajax js code , please tell me if anything is wrong in my data
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
alert(data);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
ok this is my full js code
$(document).ready(function(){
$('form#off').submit(function(event){
event.preventDefault();
if($('#name').val()==''){
$('#nameid').text('Plase Select Customer Name ');
return false;
}
else{
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
//alert('data has been added');
error: (err)=>{console.warn(err)}
// location.href='gst_chargeoff.php';
alert(data);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
The ajax call is working fine. It is also getting response from the url. If there would be any server side error , It can be detected in the error: of the ajax parameter.
In your code it was written incorrectly, the same i have corrected in the below code, you will get the error in console if there will be any server side error. else the response will be returned properly.
Check the below code.
$(document).ready(function(){
$('form#off').submit(function(event){
event.preventDefault();
if($('#name').val()==''){
$('#nameid').text('Plase Select Customer Name ');
return false;
}
else{
var formData = new FormData(this);
$.ajax({
url: '../back/regback.php',
type: 'POST',
data: formData,
success: function (data) {
//alert('data has been added');
// location.href='gst_chargeoff.php';
alert(data);
},
error: function(err){
console.log(err);
},
cache: false,
contentType: false,
processData: false
});
}
return false;
});
});
You forgot to add the error attribute to your AJAX request. It's most likely throwing an error.
error: (err) => {
console.warn(err)
}
Wrap the entire $.ajax block inside a console.log($.ajax({...}));.
Then look into the console for the response codes for more info
Also you can use this to find more about the case:
error: function(err){
console.log(err);
}

Send array of files using AJAX

Say I have an array which contains a few images:
var images = [image1, image2, image3]
How do I send these images to a php file using AJAX in a single request?
The following code did not work:
$.ajax({
url: 'PHP/posts.php',
type: 'post',
data: {data: images},
success: function(data) {
alert(data);
location.reload();
}
});
My HTML:
<div id="newPostFile">
<label for="newPostFiles"><i class="fa fa-file-text-o" id="newPostFileIcon" aria-hidden="true"></i></label>
<input type="file" name="newPostFiles" id="newPostFiles">
</div>
Endgoal:
Whenever a file is selected, the file is added to the array and when the submit button is clicked, all the files are uploaded at once.
You have to send files as formData
var images = [image1, image2, image3]
var data = new FormData();
images.forEach(function(image, i) {
data.append('image_' + i, image);
});
$.ajax({
url: 'PHP/posts.php',
type: 'post',
data: data,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
location.reload();
}
});
But as you're reloading the page anyway, why use ajax at all ?
You can pass a JSON object to PHP, which would be the convenient solution here
var data ={'image1':image1,'image2':image2};
You can pass this object to the php code and then parse it:
Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'PHP/posts.php',
data : {result:JSON.stringify(data)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "image1 : ".$data["image1"];
Another option would be serializing the array before sending, or convert it into a comma separated string using array.join, then parse/split on the posts.php
array.join(",")
you can just use the list symbol after the input name [i]
for example:
let formData = new FormData();
let files = fileInput.prop('files');
for (let i = 0; i < TotalFiles; i++) {
formData.append('file['+i+']', files[i]);
}
Use FormData Object to send files using ajax.new FormData($('#your_form_id')[0]) automatically appends all form input in FormData object which we can be done by manually formData.append('file1',file1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
let formData = new FormData($('#your_form_id')[0]);
$.ajax({
url: 'PHP/posts.php',
type: 'POST',
data: formData,
dataType:'json',
processData: false,
contentType: false,
success: function(response) {
console.log(response);
location.reload();
},
error: function() {
console.log('fail');
}
});
</script>

Ajax send array and Image in same request

I want to make an ajax call that sends both JSON and file data to my PHP backend. This is my ajax call currently:
$.ajax({
type: 'POST',
dataType: 'json',
data: jsonData,
url: 'xxx.php',
cache: false,
success: function(data) {
//removed for example
}
});
The data(jsonData) is a JSON array that also holds the input from a file select as well(I am assuming this is wrong due to the type mismatch). I tried using contentType: false, and processData: false, but when I try to access $_POST data in PHP there is nothing there. The data I am passing does not come from a form and there is quite a bit of it so I do not want to use FormData and append it to that object. I am hoping i will not have to make two ajax calls to accomplish this.
If you want to send data along with any file than you can use FormData object.
Send your jsonData as like that:
var jsonData = new FormData(document.getElementById("yourFormID"));
Than in PHP, you can check your data and file as:
<?php
print_r($_POST); // will return all data
print_r($_FILES); // will return your file
?>
Try Using formdata instead of normal serialized json
Here's an example:
var formData = new FormData();
formData.append("KEY", "VALUE");
formData.append("file", document.getElementById("fileinputID").files[0]);
then in your ajax
$.ajax({
type: 'POST',
url: "YOUR URL",
data: formData,
contentType: false,
processData: false,
dataType: 'json',
success: function (response) {
CallBack(response, ExtraData);
},
error: function () {
alert("Error Posting Data");
}
});
You can try like this also
You can visit this answer also
https://stackoverflow.com/a/35086265/2798643
HTML
<input id="fuDocument" type="file" accept="image/*" multiple="multiple" />
JS
var fd = new FormData();
var files = $("#fuDocument").get(0).files; // this is my file input in which We can select multiple files.
fd.append("kay", "value"); //As the same way you can append more fields
for (var i = 0; i < files.length; i++) {
fd.append("UploadedImage" + i, files[i]);
}
$.ajax({
type: "POST",
url: 'Url',
contentType: false,
processData: false,
data: fd,
success: function (e) {
alert("success");
}
})

Post File and data with ajax

I have read in other post on SO, similar to what is happening to me, but I still can not get the solution
$('#edit-continue').on('click', function(e) {
e.preventDefault();
var photo = new FormData(); <-----
jQuery.each(jQuery('#photo')[0].files, function(i, file) {<----- SO suggest for file upload
photo.append('file-' + i, file); <-----
});
$.ajax({
type: "POST",
url: "/templates/staycation/common/edit-profile.php",
data: {
id: $('#id').val(),
email: $('#email').val(),
birthday: $('#birthday').val(),
gender: $("input[name='gender']:checked").val(),
photo: photo,
},
success: function(data) {
console.log('pass');
console.log(data);
},
error: function(data) {
console.log('not pass');
console.log(data);
},
cache: false,
contentType: false,
processData: false, <------ i think my error is here
});
if i leave processData: false, , the post arrives empty, by making echo of my array, all data is empty, in the other case, if I comment, the console throws Uncaught TypeError: Illegal invocation
I need to do is send the values entered by the user such as "email", "gender", ... and profile picture, to make an update to the database and to save the image to a folder
this is what working perfectly for me
// formData will wrap all files and content of form
var formData=new FormData($('#formId')[0]);
// you can add more data ot formData after this to
$.ajax({
url : 'upload.php',
type : 'post',
data : formData,
processData:false,
contentType:false,
success : function(e)
{
alert('uploaded successfully');
},
error : function()
{
alert('hello from here');
}
});

ajax cannot post back node express

i am using Ajax and submitting a form. my form contains a image file which i am getting by input type file and some values from input fields. when i pass only single variable for testing is it return to success: . but when i pass form it shows error in console that it cannot post(404 not found). and shows [Object object ]in error: if i enable page refresh it shows the output on /cropImg route like this: {file_name:'filename'} i don't what i am doing wrong. i have tried many things but nothing is working its been like 3 days i am stuck here..
my Ajax form submissions
$('#cover_file_form').submit(function(e) {
var form_data = new FormData($(this)[0]);
$.ajax({
url: $(this).attr('data-url'),
type: 'post',
cache: false,
contentType: false,
processData: false,
data: form_data,
//data: {mydata:'akmal'},
//data: JSON.stringify({ "objectData":form_data}),
//async: false,
// dataType: 'json',
//contentType: "application/json",
processData: false,
success: function(ret_data) {
alert('success'+ret_data.file_name);
},
error: function(r_data) {
alert('error'+r_data);
}
});
return false;
});
and route file (routes/index.js)
app.post('/cropImg',function(req,res){
// // get the temporary location of the file
//var tmp_path = req.files['file_browse_cover'].path;
// //using graphics magick for cropping
// // gm(tmp_path)
// // .resize(500,278, "!")
// // .crop(parseInt(req.body.InputWidth),parseInt(req.body.InputHeight), parseInt(req.body.InputLeft), parseInt(req.body.InputTop))
// // .write(__dirname + "/public/images-esct/cropped/"+req.files['file_browse_cover'].name , function (err) {
// // if(err) throw err;
// // console.log(err);
// // });
// //sending file name
//fs.readFile(thisfl.path, function (err, data) {
// var newPath = __dirname + "\\eac_uploads\\" + thisfl.originalFilename;
// fs.writeFile(newPath, data, function (err) {
//res.send({ some: JSON.stringify({response:'tmp_path'}) });
//res.send({file_name:'akmal'});
// });
//});
res.send({file_name: req.files['file_browse_cover'].name});
})

Categories

Resources