When I execute the code I keep getting this error:
Uncaught TypeError: Illegal invocation
How do I fix this?
const formdata = new FormData();
for (const file of myfile.files) {
formdata.append("myFiles[]", file);
}
$.ajax({
url: '/all_backend_stuff/server.php',
type: 'POST',
data: {
"file": formdata
},
success: function(response) {
alert(response);
},
complete: function() {}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="file" id="myfile" name="myFiles[]" accept=".pdf,.jpg,.png">
When sending FormData in a jQuery AJAX request you need to supply the object directly to the data property (not as the value of a property within an object).
In addition you need to set both contentType and processData to false:
$.ajax({
url: '/all_backend_stuff/server.php',
type: 'POST',
data: formdata,
contentType: false,
processData: false,
success: function(response) {
alert(response);
},
complete: function() {}
});
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:
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();
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 am making a form submission through AJAX using jQuery. I have the following code:
$("#myForm-form").on("submit", function(event) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: {
'eoss': 'indexEOSS',
'form': 'myForm',
'values': createJSON(),
'formData': formData
},
success: function(data) {
console.log(data);
eval(data);
myFormForm(data);
},
processData: false,
contentType: false
});
return false
});
However I get this:
GET http://localhost/EOSS2/request.php?[object%20Object] 404 (Not Found)
When I remove processData: false and contentType: false I get the following error:
Uncaught TypeError: Illegal invocation
What should I do?
You have two issues here. Firstly your error message indicates that you're sending a GET request, which does not work with FormData. Using POST would seem the most applicable in this case.
Secondly, you cannot send FormData in an object as jQuery will attempt to URL encode it which will lead to issues. Instead use the append() method to add information to your FormData object. Try this:
$("#myForm-form").on("submit", function(e) {
e.preventDefault();
var $form = $(this);
var formData = new FormData($form[0]);
formData.append('eoss', 'indexEOSS');
formData.append('form', 'myForm');
formData.append('values', createJSON());
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'), // change the attribute in HTML or hardcode to 'post'
data: formData,
success: function(data) {
console.log(data);
// eval(data); < never, ever use eval()
myFormForm(data);
},
processData: false,
contentType: false
});
});
I am uploading an image using a form. For that I have to use formData. My code is returning an error:
Uncaught TypeError: Illegal invocation
Here is my code:
var url = ajaxurl,
formData = new FormData(),
_this = this,
form = $(this.$avatarForm[0]),
avatar_src = form.find('.avatar_src').val(),
avatar_data = form.find('.avatar_data').val(),
action = form.find('.action').val();
formData.append("avatar_src", avatar_src);
formData.append("avatar_data", avatar_data);
formData.append("action", action);
console.log(formData);
$.ajax(url, {
type: 'post',
data: formData,
dataType: 'json',
success: function (data) {
_this.submitDone(data);
}
});
you can try like this
$.ajax({
url : url,
type: 'post',
data: formData,
dataType: 'json',
processData: false,
success: function (data) {
_this.submitDone(data);
}
});