How to upload file in laravel with formData in jquery ajax - javascript

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

Related

Send file without form, write file in variable

Is it possible to transfer a file without form in a variable and without contentType: false, processData: false in ajax parameters ?
$(div).find('input, textarea').each(function(index, element) {
//...
var fileArr = []
if (type === 'file' && element.files.length) {
var file = $(element)[0].files[0];
var fileData = new FormData();
fileData.append('file', file);
fileArr.push(fileData);
}
//...
}
$.ajax({
type: "POST",
url: "/ajax/sendData",
success: function (data) {},
error: function (error) {},
async: true,
data: {
id: 34,
val: 34,
files: fileArr
},
cache: false,
contentType: false, //<-- without
processData: false, //<-- without
timeout: 10000
});
Illegal invocation
This is the correct syntax:
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
processData: false, // important
contentType: false, // important
dataType : 'json',
data: myFormData
});
source: https://stackoverflow.com/a/26690647/7641442
Anyway, as that answer says, you can avoid using an existing form by initializating a FormData() but it is needed to transfer files using ajax ^^
If you want to try a different approach you can try to convert the file to a string and pass it

sending values file and text inputs together with ajax to php

I have a form and it has text inputs and file input for upload an image. I tried to send values to my php page but i couldnt do it. Here is my ajax codes.
function sendval() {
var form = $('#user_update_form')[0];
var form_data = new FormData();
$.ajax({
type: 'POST',
url: 'user_update.php',
processData: false,
data: form_data,
success: function(msg) {
$('#updtalert').html(msg);
}
});
}
You should add from ajax inside this code
function sendval(){
var form = $('#user_update_form')[0];
var form_data = new FormData(this);
$.ajax({
type:'POST',
url:'user_update.php',
processData: false,
cache:false,
contentType: false,
data:form_data,
success: function (msg) {
$('#updtalert').html(msg);
}
});
}
Try below code :
function sendval(){
var form = $('#user_update_form')[0];
var form_data = new FormData(form);
$.ajax({
type:'POST',
url:'user_update.php',
processData: false,
contentType: false,
data:form_data,
success: function (msg) {
$('#updtalert').html(msg);
}
});
}

How to add variable to FormData in jquery?

Actually i am using following script to post my form
var formData = new FormData($("form#driver_information")[0]);
$.ajax({
type: "POST",
url: "/",
data: formData,
success: function(data) {
$("#page_message_box").html(data);
},
cache: false,
contentType: false,
processData: false
});
I need to pass some more variables along with form data
eg:
var formData = new FormData($("form#driver_information")[0]);
$.ajax({
type: "POST",
url: "/",
data: formData + "&con=delete",
success: function(data) {
$("#page_message_box").html(data);
},
cache: false,
contentType: false,
processData: false
});
But it's not working.( data: formData + "&con=delete", ). Please help to solve this problem.
Try this:
formData.append('con', 'delete');
before the $.ajax call.
Then within that call you just need:
data: formData,
You can append data to FormData like this:
formData.append('con', 'delete');

error when using formData jquery

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

Post files with AJAX + jQuery with input element ID

I am trying to POST form data with AJAX + jQuery using the code below
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
data.append("file_"+i, file_data[i]);
}
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input) {
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>
Here submit1 is a button on form form_id
This code is working fine, however the below line
data.append("file_"+i, file_data[i]);
as you can see posts the file with id of file_0, file_1 and so on. How can I get this to be the actual id of the input element rather than being a generic file_0, file_1 etc ?
Thanks for reading this
If you are using jQuery then why not something like this
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
Entire Code :-
<script>
$("#submit1").click(function(){
testSubmit(event);
});
function testSubmit(event) {
event.preventDefault();
var data = new FormData();
$('input[type="file"]').each(function($i){
data.append($(this).prop("id"), $(this)[0].files[0]);
});
var other_data = $('#form_id').serializeArray();
$.each(other_data,function(key,input){
data.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
}
</script>

Categories