sending values file and text inputs together with ajax to php - javascript

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

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

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

Jquery ajax upload not showing values for the big images?

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

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