I have this form:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<div class='col-sm-6' style="padding-left:0px;" >
<form action="/main/" method="post" id="my_form" enctype="multipart/form-data">
{% csrf_token %}
<br>
<div> <input type="text" name="description" id="id_description" /> </div>
<div> <input type="file" name="image" id="id_image" /> </div>
<button type="submit" disabled style="display: none" aria-hidden="true"></button>
<input class="btn btn-success" type="submit" name="submit" value="Gem" />
</form>
</div>
This successfully sends the form and it is valid on the server side. But I can´t access the image from the form on the server.
<script>
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
</script>
This solution sends the FormData with the image file, but it does not include the other form data and the form is not valid on the server side:
<script type="text/javascript">
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData();
formData.append(
"image",
document.getElementById("id_image").files[0]
);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
</script>
Is there a way to send both the file and the other form dara at the same time?
Try passing this to FormData Also, you were setting type twice.
var frm = $('#my_form');
frm.submit(function (e) {
e.preventDefault(e);
var formData = new FormData(this);
$.ajax({
async: true,
type: frm.attr('method'),
url: frm.attr('action'),
data: formData,
cache: false,
processData: false,
contentType: false,
success: function (data) {
console.log("success")
},
error: function(request, status, error) {
console.log("error")
}
});
});
Your last block using formData is only appending the file. This is why data only contains the file no other form data. Be sure to fully populate formData first.
Related
I have a simple upload file in my html like so:
<div class="col-md-12">
<span id="fileUploadErr">Please Upload A File!</span>
<div style="margin-bottom: 10px;"></div>
<input id="pickUpFileAttachment" type="file" name="attachFileObj" size="60" />
</div>
When I click on the "Submit" button the following action occurs:
$("form").submit(function() {
event.preventDefault();
var assignmentObj1 = {
selectionId: trDataSecondTable.selectionId,
inout: "in",
letterReceivedBy: $("#letterReceivedBy").val(),
letterIssuedSubBy: $("#letterIssuedSubBy").val(),
representativeNameEng: $("#representativeNameEng").val(),
letterId: 2,
assessmentNo: 0
imageFile: $("#representativeNameEng").val()
imageTitle:
}
console.log(jsonData);
$.ajax({
url: A_PAGE_CONTEXT_PATH + "/form/api/saveProcessAnexTwo",
method: "post",
contentType: "application/json",
dataType: "json",
data: JSON.stringify(assignmentObj1),
success: function(response) {
},
error: function(response) {
switch (response.status) {
case 409:
alert("error");
}
}
});
});
I need to assign the fileName and the uploaded file while sending from AJAX and need to put it inside the assignmentObj1 variable so I tried: imageFile: $("#representativeNameEng").val() to get the file information but it is not coming. How can I get the file information and send from AJAX by putting it in a local variable? And also how can I get the name of the file which can be placed in the imageTitle: property?
This is how to deal with the file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Jquery Ajax File Upload</title>
</head>
<body>
<div class="col-md-12">
<span id="fileUploadErr">Please Upload A File!</span>
<div style="margin-bottom: 10px;"></div>
<input id="pickUpFileAttachment" type="file" name="pickUpFileAttachment" size="60" />
</div>
<div class="result"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// $("form").submit(function(){
$('#pickUpFileAttachment').change(function(e){
var formData = new FormData();
formData.append('section', 'general');
formData.append('action', 'previewImg');
// Attach file
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url : window.location.pathname + "/form/api/saveProcessAnexTwo",
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false,
success: function(response){
alert("suc");
$('.result').html(response.html)
} , error: function(response){
switch(response.status){
case 409:
alert("error");
}}
});
});
//});
});
</script>
</body>
</html>
Easiest method is to use formData to send data:
var data = new FormData();
$.each($('#filecontainer')[0].files, function(i, file) {
data.append('file-'+i, file);
});
So now you have formData object
$.ajax({
url: 'php/upload.php',
data: data,
cache: false,
contentType: false,
processData: false,
method: 'POST',
type: 'POST', // For jQuery < 1.9
success: function(data){
alert(data);
}
});
Hope this helps.
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.
I am trying to send a image with AJAX.Though I keep on getting this error.
TypeError: 'append' called on an object that does not implement interface FormData.
This is my code:
$(document).ready(function(){
$('#post').on('submit', function(e){
e.preventDefault();
var data = new FormData(this);
$.ajax(
{
url: 'post_ajax/savePost',
type: 'POST',
dataType: false,
contentType: false,
pocessData: false,
data: data,
success: function (resultado) {
console.log(resultado)
}
}
).done(
function(json){
if(json.data){
console.log('Ajax correcto');
}else{
console.log('No se ha podido guardar el post');
}
}
).fail(
function(){
console.log('fallo en ajax');
}
);
});
});
And this is my html form:
<form id="post" enctype='multipart/form-data'>
<textarea id="texto" rows="4" cols="50" placeholder="¿Que esta pasando?"></textarea>
<input type="file" id="media"/>
<input type="submit" value="Submit"/>
</form>
Thanks you!!
I found this answer here:
var formData = new FormData(form[0]);
formData.append('texto', texto);
formData.append('media', archivo);
$.ajax({
url: 'post_ajax/savePost',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
Thanks everyone for all
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) {
}
});
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