jquery ajaxSubmit is not uploading file although its submitting form [duplicate] - javascript

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.

Related

Uploading Image Using JSON is not Working

Can anyone help my code structure? What's wrong with it?
HTML
<form method="post">
<div class="col-md-4">
<div class="field name-box">
<input class="btn" name="image_file" id="image_file" type="file" style="font-size:15px;width:100%;margin-bottom:2px;" required=""/>
</div>
</div>
</form>
JS
var form_data = new FormData();
$.ajax({
type: "POST",
url: baseUrlAction() + '?btn=add_product_image',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert("Successfully");
},
error: function(ts){
}
});
AJAX_CONTROLLER
public function add_product_image(){
if(is_array($_FILES)){
if(is_uploaded_file($_FILES['image_file']['tmp_name'])){
$sourcePath = $_FILES['image_file']['tmp_name'];
$targetPath = "product_images/"."sample_img_name".".png";
if(move_uploaded_file($sourcePath,$targetPath)){
// echo '<script>alert("Successfully Save")</script>';
}
}
}
}
But I've been wondering why I will get a success response on my ajax form? even my upload_file doesn't work properly. Can anyone help me?
you need to append data with form_data in your js file and send response
formData.append('image_file', $('#image_file')[0].files[0];);
var form_data = new FormData();
formData.append('image_file', $('#image_file')[0].files[0]);
$.ajax({
type: "POST",
url: baseUrlAction() + '?btn=add_product_image',
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data){
alert("Successfully");
},
error: function(){
}
});
pass form Element to FormData
let form = document.getElementById("yourFormId");
var form_data = new FormData(form);

Sending formdata for file upload using ajax

I am trying to upload an image by using form data with ajax. Though below line seems to be working fine and saving the image on my local machine.
<form ref='uploadForm' id='uploadForm' action='/tab10/uploadImage' method='post' encType="multipart/form-data">
<input type="file" class="btn btn-default" name="file" />
<input type='submit' class="btn btn-default" value='Broadcast Image' />
</form>
But when instead of specifying action as a form attribute, i try to make the call using ajax, things didn't seem to be working fine.Below is the code that i am using to make the post API call using ajax.
HTML
<form ref='uploadForm' id='uploadForm' encType="multipart/form-data">
Jquery
$("form#uploadForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
var formData = $(this).serialize();
console.log(formData);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Below is the code i am using for saving the image.
exports.uploadImage = function(req, resp) {
var res = {};
let file = req.files.file;
file.mv('./images/image', function(err) {
if (err) {
res.status = 500;
res.message = err;
// return res.status(500).send(err);
return resp.send(res);
}
res.status = 200;
res.message = 'File uploaded!';
return resp.send(res);
});
};
When i checked the request data in my uploadimage function, it seems that in the request, parameter called "files" is not being send in the later case.
I think you have to create FormData, after you can append the file to the formData, add an ID to the input <input type="file" class="btn btn-default" name="file" id="uploadFile"/>
$("form#uploadForm").submit(function (event) {
//disable the default form submission
event.preventDefault();
var formData = new FormData();
formData.append('file',$('#uploadFile')[0].files[0]);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
});
use
$("#uploadForm").submit(function () {
var formData = new FormData(this);
$.ajax({
url: '/tab10/uploadImage',
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function () {
alert('Form Submitted!');
},
error: function(){
alert("error in ajax form submission");
}
});
return false;
});
Use this format to fire ajax.because file is multipart or jquery serialize() method not serialize multipart content,so we need to put it manual.
//get choosen file
var fileContent = new FormData();
fileContent.append("file",$('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
enctype:"multipart/form-data",
url: "/tab10/uploadImage",
data: fileContent,
processData: false,
contentType: false,
success: function(response) {
}
});

Submit an ajax-created form via ajax

I'm having trouble getting an ajax-loaded form (#ajaxLoadedForm) to submit via ajax. The formData object gathers no data. I figure I've got to attach an event-handler to the form so the DOM recognizes it, but I can't figure out how.
A couple of notes: I'm bypassing the 'submit' method and using a button (#button), so I can't attach the handler to that. The form itself is a sibling to #button, not a child.
<form id="ajaxLoadedForm" enctype="multipart/form-data" action="destination.php" method="POST">
<input type="hidden" name="state" value="1" />
<label for="fullname">Your Full Name</label>
<input type="text" id="name" autocapitalize="off" autocorrect="off" name="fullname" placeholder="your name" value="" />
</form>
<div id="button">Submit me!</div>
$('#button').click(function(){
var uploadData = new FormData($("#ajaxLoadedForm")[0]);
jQuery.ajax({
url: 'destination.php',
data: uploadData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
data = JSON.parse(data);
if (data['pass'] == false) {
console.log('fail');
} else {
console.log('success');
}
}
});
});
Try using the submit handler on the form itself
$('#ajaxLoadedForm').submit(function(e){
e.preventDefault();
var uploadData = new FormData(this);
});
Then make your button for submit a submit type
<button type='submit'>Submit</button>
In your php side, test the data coming by doing this:
print_r($_POST);
you can use serialize function for sending form data . Like below
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script >
$('#button').click(function(){
var uploadData = $('#ajaxLoadedForm').serialize();
jQuery.ajax({
url: 'destination.php',
data: uploadData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
data = JSON.parse(data);
if (data['pass'] == false) {
console.log('fail');
} else {
console.log('success');
}
}
});
});
</script>
Try below code..
$('#button').click(function(){
var uploadData = new FormData();
uploadData.append('fullName',$('#fullName').val());
jQuery.ajax({
url: 'destination.php',
data: uploadData,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
}
});
});
And try to access full name in php

How to append json type data to new FormData

I have an php file like this
<form id="f-comment" class="form" method="post" action="submit_img_comment.php">
<textarea name="comment"></textarea>
<input type="submit" value="Publish" data-params='{"imageid":<?php echo $imageid; ?>}'>
</form>
I'm sending the form using jQuery ajax
$(document).on("submit", ".form", function(e) {
e.preventDefault();
// what form are you submitting?
var form = $("#" + e.target.id);
// parameters to send along with data
var params = $(this).data("params");
$.ajax({
type: form.attr("method"),
url: "include/" + form.attr("action"),
data: new FormData(this),
dataType: "json",
contentType: false,
processData: false,
cache: false
}).done(function(data) {
alert(data['msg']);
}).fail(function(data) {
alert("Error: Ajax Failed.");
}).always(function(data) {
// always do the following, no matter if it fails or not
})
});
So far so good.
The only thing missing is how to add the params to FormData. Any ideas?
Use .append(), see Using FormData Objects ; adjusting selector at declaration of params to $(input[type=submit], this) , where this is the form and .data() references .data() at input type="submit" element
$(document).on("submit", ".form", function(e) {
e.preventDefault();
var data = new FormData("form", this);
var params = $("input[type=submit]", this).data("params");
data.append("params", params);
$.ajax({
type: form.attr("method"),
url: "include/" + form.attr("action"),
data: data,
dataType: "json",
contentType: false,
processData: false,
cache: false
}).done(function(data) {
alert(data['msg']);
}).fail(function(data) {
alert("Error: Ajax Failed.");
}).always(function(data) {
// always do the following, no matter if it fails or not
})
})
The object FormData are the method append which add new parameters to the object.
For example:
var FD = new FormData('id-form');
FD.append('name','value');

File upload using Jquery ajax without form

Here is mycode
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
var startdate=$("#from_date"+elem).val();
var enddate=$("#to_date"+elem).val();
$.ajax({
url: "addpackage/",
type:"post",
contentType:false,
data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
success: function(data) {
}
});
}
I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object]. How to post image with input field without form in jquery ajax?
You can do it like following. Hope this will help you.
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('startdate', $("#from_date"+elem).val());
dataimg.append('enddate', $("#to_date"+elem).val());
dataimg.append('packageid', elem);
dataimg.append('img', $("#browseimg"+elem)[0].files[0]);
$.ajax({
url: "addpackage/",
type:"post",
cache : false,
contentType : false,
processType : false,
data: dataimg,
success: function(data) {
}
});
}
You can try this:
Your JS Code:
<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
type: "POST",
url: url,
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
</script>
Dummy HTML:
<form method="post" action="addpackage/" id="yourFormID">
<input type="text" name="firstvalue" value="some value">
<input type="text" name="secondvalue" value="some value">
<input type="file" name="imagevalue">
</form>
in addpackage php file:
print_r($_POST);
print_r($_FILES);

Categories