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});
})
Related
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);
}
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');
}
});
When I try to retrieve the File path it's shows me the result like this: "C:\fakepath\amine.jpeg" so the upload in the server is not working as a result of that problem.
$('input[type=file]').change(function () {
var filePath=$('#file-input').val();
$.ajax({
url : "{{path('upload_file')}}",
type : 'POST',
data: {
filePath : filePath,
method: 'post',
params: {
action: "uploadFile"
}
},
success : function(data, textStatus, jqXHR) {
alert(data);
}
});
});
You are doing this all wrong.
You have to create a form object and send it via $.ajax.
And I assume you have written the correct serverside code to save the image.
var f = new FormData();
f.append('img',document.getElementById("file-input").files[0]);
var url= "{{Your URL}}";
$.ajax({
url: url,
type:"post",
data: f,
dataType:"JSON",
processData: false,
contentType: false,
success: function (data, status)
{
console.log(data);
},
error: function (data)
{
if (data.status === 422) {
console.log("upload failed");
} else {
console.log("upload success");
}
});
Your file by default upload to a temporary folder. You need to move it to an actual location to get access to it like in php:
move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)
For reference, see http://www.w3schools.com/php/php_file_upload.asp
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);
}
});
I want to build an application form where on can attach an image - it's just a couple of input elements - within a div (not an form element). The form shall be processed without an page redirect. So I use ajax. Everything works fine so far. But now I need to add an image.
$('#submit_application').click(function () {
//...
$.ajax({
url: 'submit.php',
type: 'post',
data: {
'action': 'submit',
'image': $('#image_upload').val(),
// ..
'someStringifiedJSON': JSON.stringify(foo)
},
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
});
How can I get my file into php's $_FILES variable? Or how can I pass the file to php so that I can upload it?
you can send files using formData.
var file = $('#image_upload')[0].files[0];
var fData = new FormData();
fData.append('action', 'submit');
fData.append('image', file);
fData.append('someStringifiedJSON', JSON.stringify(foo));
and your ajax request will be:
$.ajax({
url: 'submit.php',
type: 'post',
data: fData ,
contentType: false,
processData: false,
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
Explanation:
as specefied here.if you set processData to true it will pass it as query string.if you want to send non-processed data set it to false.
default for contentType is application/x-www-form-urlencoded; charset=UTF-8.which won't work for files (because it sends heder like multipart/form-data; boundary=---------------------------125911542220235) when you set it to false browser generate right content-type header automatically
Try this:
$('#submit_application').click(function () {
var formData=new FormData();
formData.append('action','submit');
formData.append('someStringifiedJSON', ''+JSON.stringify(foo));
formData.append($('#image_upload').files[0]);
$.ajax({
url: 'submit.php',
type: 'post',
contentType:false,
data: formData,
success: function (data, status) {
// ...
},
error: function (xhr, desc, err) {
// ...
}
});
});
Make sure to add this contentType:false in ajax request.