form Serialize is not accepting Image in jQuery - javascript

I am trying to submit data with ajax. But form serialize is not accepting Image. Other fields are coming correctly. What is the problem?
var form = document.querySelector('form');
form.onsubmit = function(e) {
e.preventDefault();
var data = $(form).serialize();
$.ajax({
url: "{{ route('admin.faculty_tabs.store')}}",
type: 'POST',
data: data,
dataType: 'json',
processData: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(response) {
console.log(response);
},
error: function(error) {
console.log(error);
}
});

Try with
var data = new FormData(form);
And set:
{
...
processData: false,
contentType: false
}
FormData - MDN

Related

How I Can send a file with Ajax?

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/

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

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

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