How I Can send a file with Ajax? - javascript

My form is set with method=post and enctype="multipart/form-data" with regular submitting form information and photo were updated but when I want to use the Ajax ,everything have been inserted but not my photo!! What is the solution ?
$("#course-frm").submit(function(event){
event.preventDefault();
var formID = 'course-frm';
var form = $("#"+formID+'-container'+" form");
const formData = new FormData(this);
$.ajax({
url: event.target.action,
type: event.target.method,
data: formData,
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
if(data == 'success'){
sweetAlertShow('عملیات ثبت با موفقیت انجام شد', 'The operation was Successful', 'success');
form.trigger('reset');
$("#course-frm-container").load(" #course-frm-container");
}else if(data == 'unsuccess'){
sweetAlertShow('امکان ثبت وجود ندارد', 'The operation was Unsuccessful', 'error');
}
},
error: function(xhr){
var data = xhr.responseJSON;
if($.isEmptyObject(data.errors) == false) {
$.each(data.errors, function (key, value) {
$('#'+formID +'-'+ key)
.closest('.form-group')
.addClass('has-error')
.append('<span class="help-block">' + value + '</span>');
});
}
}
});
});

You need to create a form data object. In the ajax function,
set processData to `false.
Because data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
JS
$("form").submit(function(evt){
evt.preventDefault(); //prevent refresh
const formData = new FormData(this); // you need to create a FormData obj to be able to send files
$.ajax({
url: 'upload-my-files', //change this to your url
type: 'POST',
data: formData, //put formData as body data
cache: false,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
success: function (data) {
console.log(data);
}
});
});
References:
https://developer.mozilla.org/en-US/docs/Web/API/FormData
http://api.jquery.com/jquery.ajax/

Related

Php $_FILES is empty when upload with ajax

I have form with input for attachment:
<form enctype="multipart/form-data" action="" method="post" id="sendInvoiceForm">
.....
<div class="templateDiv">
<span class="invoice_email_label">Email attachments:</span>
<input name="email_attachment[]" type="file" multiple="">
</div>
<div class="templateDiv">
<button id="send_invoice_btn" class="bigButton redButton">Send</button>
</div>
</form>
And js:
data = new FormData($("#sendInvoiceForm")[0]);
data.append('flagSend', 1);
data.append('send_invoice_subject', sendInvoiceSubject);
....
$.ajax({
type: 'POST',
data: data,
processData: false,
contentType: false,
url: sJSUrlSavePdfInvoiceToServer,
dataType: 'json',
success: function (data) {
if (data.msg === 'Error. This invoice number exists.') {
alert(data.msg);
} else {
...
}
},
error: function () {
alert('error');
}
});
I tested and seems it doesnt work. All data pass well, but not file.
When I print_r $_FILES it is empty. What is my error? Thanks.
it's work for me --
var form_data = new FormData($('#submitForm')[0]);
$.ajax({
url: "<?php echo base_url() . 'backends/update_documents' ?>",
type: "POST",
dataType: 'json', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function (res) {
// console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
//console.log(xhr);
}
});
you can try with cache: false
and mention for button, type="button"
this is what i do and works
append the formdata,
var formData = new FormData(your_form);
// for multiple files , because i need to check
new_files is class, i use because i am creating form dynamically
$.each($(".new_files"), function (i, obj) {
// console.log(obj.files);
$.each(obj.files, function (j, file) {
var max_size = 5120000;
var file_type= file.type;
var match = ["image/jpeg", "image/png", "image/jpg", "application/pdf"];
// after validation etc
// append formdata
formData.append('file[' + j + ']', file);
});
});
// if you want something else,
formData.append("id", $('#kreditornr').val());
// ajax
$.ajax({
type: "POST",
url: "url",
data: formData,
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) {
// success
}
});
First remove dataType: 'json' Then if it still shows error then replace
data = new FormData($("#sendInvoiceForm")[0]);
with
data = new FormData($("#sendInvoiceForm").prop('files')[0]);
try to send the data via :
data: $('#sendInvoiceForm').serialize();

Submitted URI too large - using POST method

I am submiting a ajax request using POST method and I had got the error 414: Submitted URI too large
I had already search a possible solution to my issue but I could not resolve the issue.
There is my ajax request:
$('form[name=editClinic]').submit(function(e) {
e.preventDefault();
var url = "includes/news.php";
var form1 = $('#editClinic');
var formData = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: url,
data: formData,
async: true,
success: function (data) {
var response = data.split("||");
if(response[0] == "true"){
$.notify(response[1],"success");
}
},
error: function(chr, desc, err){
$.notify(response[1],"error");
},
cache: false,
contentType: false,
processData: false
});
});
The URL that is creted is the following one:
http://localhost/Repositories/som/administrador/noticias-editar.php?countryBanner=1&datepicker=1969-12-31+04%3A00+PM&highlight=1&typeBanner=Small&category=Tips&editor=FAMO%3ASWISS&og_img=57&title_US_EN=How+to+choose+the+right+chair%3F&subTitle_US_EN=Find+out+the+right+one+for+you.&desc_US_EN=%3Cp%3EWorking+in+an+office+usually+involves+spending+a+lot+of+time+sitting+in+a+chair.+So+how+can+you+choose+the+right+one+for+you%3F%3C%2Fp%3E%3Cp%3EThe+number+of+people+working+in+offices+is+growing.+Most+of+them+will+spend+a+whole+day+sitting+in+a+chair%2C+working+in+front+of+a+computer+screen.%3C%2Fp%3E%3Cp%3EHowever%2C+this+position+is+detrimental+to+your+health.+Back+problems+arising+from+the+amount+of+time+spent+in+that+position+has+become+a+common+complaint.%3Cbr%3E%3C%2Fp%3E%3Cp%3EHow+can+you+avoid+such+problems%3F%3Cbr%3E%3C%2Fp%3E%3Cp%3ETo+avoid+the+emergence+of+back+problems%2C+preventive+action+must+be+taken.+One+form+of+action+is+to+be+careful+with+your+posture.+But+equally+important+is+the+choice+of+an+ergonomic+chair%3B+it+should+respond+to+the+demands+of+your+body+and+spine%2C+and+supports+and+promotes+good+posture.%3Cbr%3E%3C%2Fp%3E%3Cp%3EWhat+features+should+the+chair+have%3F%3Cbr%3E%3C%2Fp%3E%3Cp%3E1.+It+should+be+adjustable+%E2%80%93+In+terms+of+sitting+height%2C+arm+length%2C+and+inclination%2C+among+others.+The+greater+the+adjustment+options%2C+the+greater+the+likelihood+that+it+will+be+compatible+to+your+needs.%3Cbr%3E%3C%2Fp%3E%3Cp%3E2.+Keep+back+support+in+mind%E2%80%93+If+you+spend+many+hours+sitting%2C+it+is+important+that+the+chair+accommodates+the+curvature+of+your+spine.%3Cbr%3E%3C%2Fp%3E%3Cp%3E3.+Take+upholstering+into+account+%E2%80%93+The+material+of+the+chair+should+be+sufficiently+padded+to+be+comfortable+for+long+periods+of+time.+A+leather+covering+is+more+resistant+but+a+covering+in+fabric+is+healthier+because+it+breathes+better.%3Cbr%3E%3C%2Fp%3E%3Cp%3E4.+Try+different+chairs+%E2%80%93+Don%E2%80%99t+just+read+about+features+of+the+chair+before+you+buy+it.+It+is+important+to+actually+try+out+various+chairs%2C+sitting+in+them%2C+to+see+which+best+suits+your+needs.%3Cbr%3E%3C%2Fp%3E%3Cp%3ESo+now+the+next+time+you+need+to+buy+one+you+know+how+to+choose+the+best+one+for+your+health.%3C%2Fp%3E&idTrans_US_EN=37&title_US_ES=%C2%BFC%C3%B3mo+elegir+la+silla+correcta%3F&subTitle_US_ES=Encuentra+el+m%C3%A1s+adecuado+para+ti.&desc_US_ES=%3Cp%3ETrabajar+en+una+oficina+es+una+tarea+que%2C+normalmente%2C+requiere+pasar+mucho+tiempo+sentado+en+una+silla.+%C2%BFExiste+alguna+forma+para+elegir+la+silla+m%C3%A1s+adecuada+para+usted%3F%3C%2Fp%3E%3Cp%3E%C2%A0En+los+d%C3%ADas+de+hoy%2C+el+n%C3%BAmero+de+personas+que+trabajan+en+oficinas+ha+crecido.+La+mayor%C3%ADa+de+ellas+pasa+el+d%C3%ADa+entero+sentadas+en+una+silla%2C+trabajando+delante+de+una+pantalla.%3C%2Fp%3E%3Cp%3ESin+embargo%2C+%C3%A9sta+es+una+posici%C3%B3n+que+no+es+muy+buena+para+su+salud.+Comienza+a+ser+frecuente+el+aparecimiento+de+problemas+en+la+columna+por+causa+del+tiempo+que+se+pasa+en+esta+posici%C3%B3n.%3Cbr%3E%3C%2Fp%3E%3Cp%3E%3Cb%3E%C2%BFSe+pueden+evitar+estos+problemas%3F%3Cbr%3E%3C%2Fb%3E%3C%2Fp%3E%3Cp%3EPara+evitar+el+aparecimiento+de+estos+problemas%2C+deben+tomarse+algunas+actitudes+preventivas.%C2%A0+Una+de+ellas+es+tener+cuidado+con+su+postura.+Pero+tambi%C3%A9n+es+muy+importante+la+elecci%C3%B3n+de+una+silla+ergon%C3%B3mica.+Una+silla+capaz+de+responder+a+las+exigencias+de+su+cuerpo+y+de+su+columna%2C+y+adem%C3%A1s+que%C2%A0+le+ofrece+el+soporte+y+promueve+una+buena+postura.%3Cbr%3E%3C%2Fp%3E%3Cp%3E%3Cb%3E%C2%BFC%C3%B3mo+debe+ser+su+silla%3F%3Cbr%3E%3C%2Fb%3E%3C%2Fp%3E%3Cp%3E1.+Debe+permitir+ajustarse+a+su+medida+%E2%80%93+a+su+altura+del+asiento%2C+de+los+brazos%2C+la+inclinaci%C3%B3n%2C+entre+otros.+Cuanto+mayor+sea+la+posibilidad+de+los+ajustes%2C+mayor+es+la+probabilidad+de+que+sea+compatible+con+sus+necesidades.%3Cbr%3E%3C%2Fp%3E%3Cp%3E2.+Tenga+en+cuenta+el+soporte+para+su+espalda+%E2%80%93+si+pasa+muchas+horas+sentado%2C+es+importante+que+la+silla+acompa%C3%B1e+la+curvatura+de+su+columna.%3Cbr%3E%3C%2Fp%3E%3Cp%3E3.+Tenga+en+cuenta+el+material+%E2%80%93+el+material+de+la+silla+debe+tener+la+consistencia+suficiente+para+ser+c%C3%B3moda+durante+largos+periodos+de+tiempo.+El+revestimiento+en+piel+es+m%C3%A1s+resistente%2C+pero+en+tela+es+m%C3%A1s+saludable+porque+permite+una+mejor+transpiraci%C3%B3n.+%3C%2Fp%3E%3Cp%3E4.+Experimente%2C+pruebe+diferentes+sillas+%E2%80%93+no+lea+apenas+las+caracter%C3%ADsticas+de+la+silla+antes+de+comprarla.+Es+importante+sentarse+en+diferentes+sillas+para+saber+cu%C3%A1l+es+la+que+mejor+se+adapta+a+sus+necesidades.%3C%2Fp%3E%3Cp%3ELa+pr%C3%B3xima+vez+que+tenga+que+comprar+una+silla%2C+ya+sabe+c%C3%B3mo+elegir+la+que+es+mejor+para+su+salud.%3Cbr%3E%3C%2Fp%3E&idTrans_US_ES=38&title_US_PT=%C2%BFC%C3%B3mo+elegir+la+silla+correcta%3F&subTitle_US_PT=%C2%BFC%C3%B3mo+elegir+la+silla+correcta%3F&desc_US_PT=%3Cp%3E%C2%BFC%C3%B3mo+elegir+la+silla+correcta%3F%3Cbr%3E%3C%2Fp%3E&idTrans_US_PT=39&cmdEval=editNews&idNews=16&bot=
Can anyone help me?

How to upload file in laravel with formData in jquery ajax

I am using laravel 5.4 and jquery Ajax to upload file and some form data.
I am using below code
function submitDocument(){
var formData = new FormData(); // Currently empty
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "documents",
method: "post",
data:{_token,formData},
}).done(function(data) {
});
return false;// Not to submit page
}
And I am getting error
Uncaught TypeError: Illegal invocation
How can I fix this ? Thanks in advance for your time.
I am able to get value in formData by using
console.log(formData.get('title'));
console.log(formData.get('doc'));
Try adding processData: false, contentType: false in your code
Replace your script with this:
function submitDocument(){
var formData = new FormData(); // Currently empty
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "documents",
method: "post",
data:{_token,formData},
cache : false,
processData: false,
contentType: false
}).done(function(data) {
});
return false;// Not to submit page
}
By default, data passed in to the data option as an object will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
<script>
$(document).ready(function() {
var url = "{{ url('/admin/file') }}";
var options = {
type: 'post',
url: url,
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}'},
dataType: 'doc',
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert('Ok');
},
error: function (data) {
alert('Error');
}
};
$('#save').on('click', function() {
$("#form").ajaxSubmit(options);
return false;
});
});
</script>
Try this way
$(document).ready(function (){
$("#form").on('submit',(function(e){
e.preventDefault();
var formdata = new FormData(this);
var _token = $("#_token").val().trim();
formData.append('title', $("#title").val());
formData.append("doc",$("#doc")[0].files[0]);
$.ajax({
url: "/site/url",
type: "POST",
data:{token:_token,formData},
contentType: false,
cache: false,
processData:false,
success: function(data){
},
});
}));});

How to append json type data to new FormData

I have an php file like this
<form id="f-comment" class="form" method="post" action="submit_img_comment.php">
<textarea name="comment"></textarea>
<input type="submit" value="Publish" data-params='{"imageid":<?php echo $imageid; ?>}'>
</form>
I'm sending the form using jQuery ajax
$(document).on("submit", ".form", function(e) {
e.preventDefault();
// what form are you submitting?
var form = $("#" + e.target.id);
// parameters to send along with data
var params = $(this).data("params");
$.ajax({
type: form.attr("method"),
url: "include/" + form.attr("action"),
data: new FormData(this),
dataType: "json",
contentType: false,
processData: false,
cache: false
}).done(function(data) {
alert(data['msg']);
}).fail(function(data) {
alert("Error: Ajax Failed.");
}).always(function(data) {
// always do the following, no matter if it fails or not
})
});
So far so good.
The only thing missing is how to add the params to FormData. Any ideas?
Use .append(), see Using FormData Objects ; adjusting selector at declaration of params to $(input[type=submit], this) , where this is the form and .data() references .data() at input type="submit" element
$(document).on("submit", ".form", function(e) {
e.preventDefault();
var data = new FormData("form", this);
var params = $("input[type=submit]", this).data("params");
data.append("params", params);
$.ajax({
type: form.attr("method"),
url: "include/" + form.attr("action"),
data: data,
dataType: "json",
contentType: false,
processData: false,
cache: false
}).done(function(data) {
alert(data['msg']);
}).fail(function(data) {
alert("Error: Ajax Failed.");
}).always(function(data) {
// always do the following, no matter if it fails or not
})
})
The object FormData are the method append which add new parameters to the object.
For example:
var FD = new FormData('id-form');
FD.append('name','value');

ajax form submit redirect like a not ajax form

I have this code that I use to submit a form with a attachment file
$("#career_form").submit(function(e){
var this_current = $(this);
var formData = new FormData(this_current[0]);
var url = this_current.attr("action");
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
e.preventDefault();
});
but the form keeps redirecting me to its destination file "url in the action" like it wasn't an ajax submission but if I replace the 'data' argument with
data: $(this).serialize();
it works (ajax submit), any ideas, help, suggestions, recommendations?
give that e.preventDefault(); at the beginning of the function.
jQuery trys to transform your data by default into a query string, but with new formData it throws an error.
To use formData for a jquery ajax request use the option processData and set it to false like:
$.ajax({
url : url,
data: formData,
type: 'post',
cache: false,
async: true,
processData: false,
beforeSend: function(){ },
success: function(response){
if(response === true){
alert("successfully sent");
}
}
});
Thats the reason why it works with serialize, but not with formData in your example.
The e.preventDefault works correctly, but if there is an error before it will not work. By placing the e.preventDefault at the top of your function it will allways prevent the action, no matter if there is an error in later code or not.
You can edit the var formData = new FormData(this_current[0]); in your code and use the below line:
var formData = new FormData(document.querySelector("#career_form"));
Also, if you are using multipart form to send files in your form, you need to set following parameters in your ajax call.
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
Hope this helps. See more about using formData here.
Try this:
$("#career_form").submit(function(e){
e.preventDefault();
var fd = new FormData(document.querySelector("form"));
fd.append("CustomField", "This is some extra data");
$.ajax({
url: "change-status.php",
type: "POST",
data: fd,
processData: false,
contentType: false,
success: function(response){
if(response){
alert("successfully sent");
}
}
});
});

Categories