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();
Related
I've got an ajax function:
$('#addSiteButton').on('click',function() {
let addSiteOption = $('#enterNewWebsiteLink').val();
const form = new FormData();
form.append('addSiteOption', addSiteOption);
$.ajax({
url: "includes/submit_site.php",
data: { 'data': form },
method: "POST",
contentType: false,
processData: false,
enctype: false,
cache: false,
datatype: "text",
success: function (response, data) {
}
});
My PHP file looks just like this:
if (isset($_POST['data'])) {
$websitelink = $_POST['addSiteOption'];
}
my HTML looks like this:
<input type="url" form="addsite" class="enterNewWebsiteLink"
id="enterNewWebsiteLink"
name="enterwebsitelink"
placeholder="Enter A New Website">
The error that I am getting is: Warning: Undefined array key "data"
I've tried outputting the variable addSiteOption and it outputs the URL correctly.
The frustrating thing, I've been checking/copying this against a previous project I did that I got it working in, and I can't make any difference between them now.
I get a 200 response from the server for the page.
You can't serialize FormData, and processData: false tells jQuery not to try to serialize the data: option.
You should just pass the FormData as the data: option. Then the keys of the FormData will become the $_POST keys.
JS:
$('#addSiteButton').on('click',function() {
let addSiteOption = $('#enterNewWebsiteLink').val();
const form = new FormData();
form.append('addSiteOption', addSiteOption);
$.ajax({
url: "includes/submit_site.php",
data: form,
method: "POST",
contentType: false,
processData: false,
enctype: false,
cache: false,
dataType: "text",
success: function (response, data) {
}
});
PHP:
if (isset($_POST['addSiteOption'])) {
$websitelink = $_POST['addSiteOption'];
}
You also had a typo: datatype: should be dataType:
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/
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){
},
});
}));});
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');
I have a page where i have send form data using jquery ajax upload and in php file i am posting these values in database but it is not showing any values for big image in php files when i try to print . Please check with the my screen shot. upload image size 2mb
var formData = new FormData($('form')[0]);
formData.append('licens_certificate', licens_certificate);
$.ajax({
url: "<?php echo site_url(); ?>pro/submit_business",
type: "POST",
data:formData,
async: false,
processData : false,
contentType : false,
// fileElementId :'licens_certificate',
dataType: "json",
// contentType: 'multipart/form-data',
success: function(result){
alert()
}
});
Please check data properly append with formdata.
var formData = new FormData($('form')[0]);
formData.append('licens_certificate', licens_certificate);
$.ajax({
url: "pro/submit_business",
type: "POST",
data:formData,
async: false,
processData : false,
contentType : false,
// fileElementId :'licens_certificate',
dataType: "json",
// contentType: 'multipart/form-data',
success: function(result){
alert(result)
}
});
Edit: Here's how you convert your form to JSON:
var serializeJSON = function(formData) {
var jsonData = {};
$.each(formData, function() {
if (jsonData[this.name]) {
if (!jsonData[this.name].push) {
jsonData[this.name] = [jsonData[this.name]];
}
jsonData[this.name].push(this.value || '');
} else {
jsonData[this.name] = this.value || '';
}
});
return jsonData;
}
var formData = $("#myform").serializeArray();
var json = serializeJSON(formData);
// Add your licens_certificate data
json['licens_certificate' = 'licens_certificate';
$.ajax({
url: "<?php echo site_url(); ?>pro/submit_business",
type: "POST",
data: json,
async: false,
processData : false,
contentType : false,
dataType: "json",
success: function(result){
alert()
},
error: function(err) {
console.log(err);
}
});
Original
Have you tried to serialize your form?
var formData = $('form').serializeArray();
formData.push({licens_certificate:, 'licens_certificate'});
$.ajax({
url: "<?php echo site_url(); ?>pro/submit_business",
type: "POST",
data: formData,
async: false,
processData : false,
contentType : false,
dataType: "json",
success: function(result){
alert()
},
error: function(err) {
console.log(err);
}
});
Also, make sure you are serializing the right form, especialy if you have several in your page.
You could also simply use the $.post function
var url = "<?php echo site_url(); ?>pro/submit_business";
$.post(url, dataForm).succes(function(data) { alert(); });