Ajax Image upload using serialize method - javascript

Here I have used serialize method to fetch the data but I am not getting image from that please help to find the solution or give me alternative of serialize method.
$( "#button" ).click(function(){
$.ajax({
type: 'POST',
url: ajax_url,
enctype: 'multipart/form-data',
data:{
data_array:$( "#form" ).serialize(),
action: 'product_add_form_submit'
},
success: function (data) {
alert('Successfully Submitted');
}
});
});

You can upload Form fields with file as mentioned below, and follow comment.
$('#my-form').submit( function( e ) {
form_data= new FormData($(this)[0]);
var imgFile = $("file_input_selector")[0]; // change your delector here
form_data.append("file_name_field", imgFile.files[0]); // change filename field here
$.ajax({
url: 'http://host.com/action/',
type: 'POST',
data: form_data,
success: function(data){
alert(data);
}
});
e.preventDefault();
});

( '#my-form' )
.submit( function( e ) {
$.ajax( {
url: 'http://host.com/action/',
type: 'POST',
data: new FormData( this ),
processData: false,
contentType: false
} );
e.preventDefault();
} );

//html form
<form action="url" id="addquestionsamepage" class="form-horizontal form-label-left" method="post" enctype="multipart/form-data" accept-charset="utf-8">
<div class="item form-group">
<label class="control-label col-md-3 col-sm-3 col-xs-12">Image </label>
<div class="col-md-6 col-sm-6 col-xs-12">
<input class="form-control col-md-7 col-xs-12" name="image" id="add_image" type="file">
</div>
</div>
</form>
//jquery code
$('#addquestionsamepage').submit(function (e) {
e.preventDefault();
var form = $("#addquestionsamepage");
var url = form.attr('action');
var formData = new FormData(this);
$.ajax({
type: "POST",
url: url,
data: formData,
cache:false,
contentType: false,
processData: false,
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});

Related

How to upload multiple images with ajax?

I am trying to upload multiple image files. Please check out my code.
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" id="images_input">
</from>
$(document).ready(function(){
$('body').on('submit', '#fileupload', function(e){
e.preventDefault();
var files = document.getElementById("images_input").files;
var files_array = [];
$(files).each(function(index, value){
files_array.push(value);
// files_array.push(value);
});//each
var user_id = $("#user_id_input").val();
var product_name = $("#product_name_input").val();
console.log("Data",files[0]);
var url = "../filemanager/s3_laravel/public/upload";
$.ajax({
url: url,
data:{
files:files_array,
user_id: user_id,
product_name: product_name
},
type: 'POST',
success: function(data){
alert(data);
}
});
});
$('#images_input').change(function(){
$("#fileupload").submit();
});//change
When I try to submit it I get this error https://prnt.sc/l8vmhn. Please help in this regard.
Adding processData: false to your options object fixes the error.
You need to use the FormData API. Like this.
<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" name="files[]" multiple="multiple" id="images_input">
</form>
<script>
$(document).ready(function(){
$('body').on('submit', '#fileupload', function(e){
e.preventDefault();
var formData = new FormData();
var files = document.getElementById("images_input").files;
$(files).each(function(index, value){
formData.append('files[]', value);
});
formData.append('user_id', $("#user_id_input").val());
formData.append('product_name', $("#product_name_input").val());
var url = "../filemanager/s3_laravel/public/upload";
$.ajax({
type: 'POST',
url: url,
contentType: false,
processData: false,
data: formData,
success: function(data){
alert(data);
}
});
});
$('#images_input').change(function(){
$("#fileupload").submit();
});
</script>
Finally It worked like this:
$(document).ready(function(){
$('#images_input').change(function(){
$("#fileupload").submit();
});//change
$("#fileupload").on('submit',function(event) {
event.preventDefault();
var formData = new FormData(this);
var url = "../filemanager/s3_laravel/public/upload";
$.ajax({
url: url,
type: "POST",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(data) {
console.log(data);
}
});//
});//submit
});//ready

file and form upload with ajax and jquery

How I to for send an image and form with a request ajax?
HTML
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
</form>
<button id="btnSave">Save</button>
JQuery - AJAX
$("#btnSave").click(function()
{
var Url = 'http://localhost/systemm/public/painel/client';
var Dados = $('#FormClient').serialize();
$.ajax({
type:Type,
url: Url,
dataType: 'JSON',
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
});
When I serialize the data and put in an alert to display I see that the image is not there, how do I send the image along with my form to my server/controller?
Use formData object:
HTML
<form enctype="multipart/form-data">
<input type="text" class="form-control" id="Name" name="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button id="btnSave">Save</button>
</form>
JS
$("#btnSave").click(function() {
var Url = 'http://localhost/systemm/public/painel/client';
var formData = new FormData(this.form);
$.ajax({
type:'post',
url: Url,
dataType: 'JSON',
data: formData,
...
});
});
Let's try following,
<form id="POST_FORM" method="post" enctype="multipart/form-data" >
<input type="text" class="form-control" id="Name"/>
<input type="file" name="imgClient" class="form-control" id="UploadIMG"/>
<button type="submit" id="btnSave">Save</button>
</form>
$("#POST_FORM").submit(function(){
var data = new FormData(this);
addPOST(data);
return false;
});
function addPOST(formData){
$.ajax({
type:'POST',
url: Url,
data:formData,
dataType:"json",
cache:false,
contentType: false,
processData: false,
success:function(response){
},
error: function(data){
console.log("error");
console.log(data);
}
});
}
Try to change content dataType. Set dataType='false'
$.ajax({
type:Type,
url: Url,
dataType: false,
data: Dados,
success:function(data){
if($.isEmptyObject(data.error))
location.reload();
else
printErrorMsg(data.error);
},
error:function(e){
alert('Ocorreu um erro !');
console.log(e);
},
});
Hope this helps
This is the way i have done it.
var obj = document.getElementById('my_form_id')
var data = new FormData(obj);
$.ajax({
type: 'post',
url: $(obj).parent().attr('action'),
processData: false,
contentType: false,
data: data,
success: function(result){
profile_app.user.foto_url = result.url
},
error: function(error){
console.log("error");
}
});

Jquery Serialize with File

Hi this code isn't working. Im using this serialize(); method but when I add an input type of file it isn't working. But if no file its working. Please help me.
$("#resimBtn").on("click", function(){
var dresim = $("#resimForm").serialize();
$.ajax({
url: "ayarlar/islem.php?islem=resim",
type: 'POST',
data: dresim ,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(cevap){
$("#resimAlert").html(cevap).hide().fadeIn(700);
}
});
});
<form id="resimForm" class="form-horizontal form-bordered" >
<div class="form-group">
<label class="col-md-3 control-label" for="inputDefault">Kategori Durum</label>
<div class="col-md-6">
<input type="file" name="resim">
</div>
</div>
<div class="col-md-6 col-md-offset-3">
<div id="resimBtn" class="btn btn-primary btn-lg pull-right">Ekle</div>
</div>
</form>
In the data key inside the Ajax call function, use a form data.
var form = $('#resimForm')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
data: formData,
Alternatively you can use a submit handler.
$('#resimForm').submit(function(e) {
e.preventDefault();
$.ajax({
//other Ajax stuff
data: new FormData(this),
});
});
USE this:
var formData = new FormData($('#resimForm')[0]);
$("#resimBtn").on("click", function(){
$.ajax({
url: "ayarlar/islem.php?islem=resim",
type: 'POST',
data: formData ,
async: false,
cache: false,
contentType: false,
processData: false,
success: function(cevap){
$("#resimAlert").html(cevap).hide().fadeIn(700);
}
});
});

Ajax form with file submission [duplicate]

This is my HTML which I'm generating dynamically using drag and drop functionality.
<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>
<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
This is my JavaScript code:
<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);
$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.
Note: contentType: false only available from jQuery 1.6 onwards
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: base_url + "member/upload/",
data: formData,
//use contentType, processData for sure.
contentType: false,
processData: false,
beforeSend: function() {
$('.modal .ajax_data').prepend('<img src="' +
base_url +
'"asset/images/ajax-loader.gif" />');
//$(".modal .ajax_data").html("<pre>Hold on...</pre>");
$(".modal").modal("show");
},
success: function(msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function() {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
); //
$('#done').hide();
}
});
you can use.
var form = $('form')[0];
var formData = new FormData(form);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").
$.ajax( {
url: "http://yourlocationtopost/",
type: 'POST',
data: new FormData(document.getElementById("yourFormElementID")),
processData: false,
contentType: false
} ).done(function(d) {
console.log('done');
});
$('#form-withdraw').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'function/ajax/topup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata == 'success')
{
swal({
title: "Great",
text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
},
function(){
window.location.href = '/transaction.php';
});
}
else if(returndata == 'Offline')
{
sweetAlert("Offline", "Please use other payment method", "error");
}
}
});
});
Actually The documentation shows that you can use XMLHttpRequest().send()
to simply send multiform data
in case jquery sucks
View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
$(document).on('change', ':file', function () {
var fileUpload = $(this).get(0);
var files = fileUpload.files;
var bid = 0;
if (files.length != 0) {
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
xhr: function () {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (e) {
console.log(Math.floor(e.loaded / e.total * 100) + '%');
};
return xhr;
},
contentType: false,
processData: false,
type: 'POST',
data: data,
url: '/ControllerX/' + bid,
success: function (response) {
location.href = 'xxx/Index/';
}
});
}
});
});
</Script>
Controller:
[HttpPost]
public ActionResult ControllerX(string id)
{
var files = Request.Form.Files;
...
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.

How to use FormData for AJAX file upload?

This is my HTML which I'm generating dynamically using drag and drop functionality.
<form method="POST" id="contact" name="13" class="form-horizontal wpc_contact" novalidate="novalidate" enctype="multipart/form-data">
<fieldset>
<div id="legend" class="">
<legend class="">file demoe 1</legend>
<div id="alert-message" class="alert hidden"></div>
</div>
<div class="control-group">
<!-- Text input-->
<label class="control-label" for="input01">Text input</label>
<div class="controls">
<input type="text" placeholder="placeholder" class="input-xlarge" name="name">
<p class="help-block" style="display:none;">text_input</p>
</div>
<div class="control-group"> </div>
<label class="control-label">File Button</label>
<!-- File Upload -->
<div class="controls">
<input class="input-file" id="fileInput" type="file" name="file">
</div>
</div>
<div class="control-group">
<!-- Button -->
<div class="controls">
<button class="btn btn-success">Button</button>
</div>
</div>
</fieldset>
</form>
This is my JavaScript code:
<script>
$('.wpc_contact').submit(function(event){
var formname = $('.wpc_contact').attr('name');
var form = $('.wpc_contact').serialize();
var FormData = new FormData($(form)[1]);
$.ajax({
url : '<?php echo plugins_url(); ?>'+'/wpc-contact-form/resources/js/tinymce.php',
data : {form:form,formname:formname,ipadd:ipadd,FormData:FormData},
type : 'POST',
processData: false,
contentType: false,
success : function(data){
alert(data);
}
});
}
For correct form data usage you need to do 2 steps.
Preparations
You can give your whole form to FormData() for processing
var form = $('form')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
or specify exact data for FormData()
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
Sending form
Ajax request with jquery will looks like this:
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
After this it will send ajax request like you submit regular form with enctype="multipart/form-data"
Update: This request cannot work without type:"POST" in options since all files must be sent via POST request.
Note: contentType: false only available from jQuery 1.6 onwards
I can't add a comment above as I do not have enough reputation, but the above answer was nearly perfect for me, except I had to add
type: "POST"
to the .ajax call. I was scratching my head for a few minutes trying to figure out what I had done wrong, that's all it needed and works a treat. So this is the whole snippet:
Full credit to the answer above me, this is just a small tweak to that. This is just in case anyone else gets stuck and can't see the obvious.
$.ajax({
url: 'Your url here',
data: formData,
type: "POST", //ADDED THIS LINE
// THIS MUST BE DONE FOR FILE UPLOADING
contentType: false,
processData: false,
// ... Other options like success and etc
})
<form id="upload_form" enctype="multipart/form-data">
jQuery with CodeIgniter file upload:
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: base_url + "member/upload/",
data: formData,
//use contentType, processData for sure.
contentType: false,
processData: false,
beforeSend: function() {
$('.modal .ajax_data').prepend('<img src="' +
base_url +
'"asset/images/ajax-loader.gif" />');
//$(".modal .ajax_data").html("<pre>Hold on...</pre>");
$(".modal").modal("show");
},
success: function(msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function() {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
); //
$('#done').hide();
}
});
you can use.
var form = $('form')[0];
var formData = new FormData(form);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
or
var formData = new FormData($('#upload_form')[0]);
formData.append('tax_file', $('input[type=file]')[0].files[0]);
Both will work.
$(document).ready(function () {
$(".submit_btn").click(function (event) {
event.preventDefault();
var form = $('#fileUploadForm')[0];
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "upload.php",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
console.log();
},
});
});
});
Better to use the native javascript to find the element by id like: document.getElementById("yourFormElementID").
$.ajax( {
url: "http://yourlocationtopost/",
type: 'POST',
data: new FormData(document.getElementById("yourFormElementID")),
processData: false,
contentType: false
} ).done(function(d) {
console.log('done');
});
$('#form-withdraw').submit(function(event) {
//prevent the form from submitting by default
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'function/ajax/topup.php',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (returndata) {
if(returndata == 'success')
{
swal({
title: "Great",
text: "Your Form has Been Transfer, We will comfirm the amount you reload in 3 hours",
type: "success",
showCancelButton: false,
confirmButtonColor: "#DD6B55",
confirmButtonText: "OK",
closeOnConfirm: false
},
function(){
window.location.href = '/transaction.php';
});
}
else if(returndata == 'Offline')
{
sweetAlert("Offline", "Please use other payment method", "error");
}
}
});
});
Actually The documentation shows that you can use XMLHttpRequest().send()
to simply send multiform data
in case jquery sucks
View:
<label class="btn btn-info btn-file">
Import <input type="file" style="display: none;">
</label>
<Script>
$(document).ready(function () {
$(document).on('change', ':file', function () {
var fileUpload = $(this).get(0);
var files = fileUpload.files;
var bid = 0;
if (files.length != 0) {
var data = new FormData();
for (var i = 0; i < files.length ; i++) {
data.append(files[i].name, files[i]);
}
$.ajax({
xhr: function () {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function (e) {
console.log(Math.floor(e.loaded / e.total * 100) + '%');
};
return xhr;
},
contentType: false,
processData: false,
type: 'POST',
data: data,
url: '/ControllerX/' + bid,
success: function (response) {
location.href = 'xxx/Index/';
}
});
}
});
});
</Script>
Controller:
[HttpPost]
public ActionResult ControllerX(string id)
{
var files = Request.Form.Files;
...
Good morning.
I was have the same problem with upload of multiple images. Solution was more simple than I had imagined: include [] in the name field.
<input type="file" name="files[]" multiple>
I did not make any modification on FormData.

Categories

Resources