Post File and data with ajax - javascript

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

Related

how to append formdata in ajax call with image in php?

I want to send FirstName, LastName and Image through Ajax Call to PHP. I am able to send the data without image, and I am able to send the image without text using formdata but the problem is I am not able to do both at a time. Kindly check my code what I am doing wrong:
<script>
function createBasicInfo() {
// For Image Send
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
// For Text Send
var data = {
'firstname' : jQuery('#firstname').val(),
'lastname' : jQuery('#lastname').val(),
};
**//Here Is the Problem, I am not able to append the data with Text**
formdata.append(data);
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
if (data != 'passed') {
jQuery('#modal_errors_1').html(data);
}
if (data == 'passed') {
jQuery('#modal_errors_1').html("");
location.reload();
}
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>
In above code if I comment
//formdata.append(data); // Then only image will send to php
And If I use in Ajax Call
data: data, // Then only FirstName & LastName will send to php without Image
I am not able to send text data and image both at the same time to php file.
Any idea or suggestion would be welcome.
You could just do this insted of formdata.append(data):
formdata.firstname = jQuery('#firstname').val();
formdata.lastname = jQuery('#lastname').val();
Just append your firstname and lastname into formdata. Then send full formdata.
<script>
function createBasicInfo() {
var formdata = new FormData();
var file = jQuery('#photo').prop('files')[0];
formdata.append('photo', file);
formdata.append('firstname', jQuery('#firstname').val());
formdata.append('lastname', jQuery('#lastname').val());
//Ajax call Start Here
jQuery.ajax({
url: '/adminseller/parsers/sbasicinfo.php',
method: 'POST',
cache: false,
contentType: false,
processData: false,
data: formdata,
success: function(data) {
// ...
// ...
},
error: function() {
alert("Something went wrong.");
},
});
}
</script>

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

Fake path Javascript Issue

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

How do file upload for Ajax

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

jQuery Submit Form (w/ file and text) without redirecting from current window

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.

Categories

Resources