I'm trying to upload a file and some inputs in a form via ajax. I'm using CI and used AjaxFileUpload plugin for file upload. I'm getting
Uncaught TypeError: $.ajaxFileUpload is not a function
HTML:
<form id="importtableform" class="form form-group" method="post">
Table Name: <select class="form-control" id="tableName">
<option disabled>--Select Table--</option>
</select>
<div class="form-group" style="margin-top:0px !important;">
<input class="form-control meta" name="csvFile" id="csvFile" type="file" style="cursor: pointer;" accept=".csv">
</div>
</form>
<button type="button" id="upload" class="btn-modal btn btn-block btn-primary">Upload</button>
JS:
$('#upload').click(function () {
var fileObj = $('#csvFile')[0].files[0];
var tableName = $('#tableName').find(':selected').val();
$.ajaxFileUpload({
type: 'POST',
url: baseurl + '/rest/bulkUpload',
data: {
'tableName': tableName
},
fileElementId :'csvFile',
processData: false,
contentType: false,
success: function (result) {
console.log(result);
}
});
});
EDIT
I tried formData() with plain ajax before using this third party plugin, in that case I got another error
$this->upload->display_errors()
You did not select a file to upload.
Related
I'm trying to upload multiple files using jquery and PHP.
But my form data is not being submitted as required to the PHP page.
Please, can someone help me out writing the correct way of uploading files?
Below is my code:
index.php:
<form id="step17Form" action="" name="step17Form" method="post" enctype="multipart/form-data">
<div style="text-align :left; margin-left:15px"> <label><big>
(<span style="color: red; font-family: Comic Sans MS;"><small style="font-weight: bold;">Note: Max File Size - 75KB</small></span>)</big></label>
<br><br>
<table style="text-align: centre; width: 800px; margin-left:15px" border="0" id="upload" cellpadding="6" cellspacing="6">
<tbody>
<tr>
<td><br><label for="stuphoto"><span style="font-family: Comic Sans MS;">1. Student Photo</label></span>
</td>
<td><br><input id="file-upload" name="stuphoto" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
</tr>
<tr>
<td><br><label for="stuadhar"><span style="font-family: Comic Sans MS;">2. Aadhar Card</label></span>
</td>
<td><br><input name="stuadhar" accept=".jpg,.pdf" class="custom-file-upload" type="file" style="display: inline;"></td>
</tr>
</tbody>
</table>
</div>
<br>
<input type="hidden" name="reason" value="step17" />
<button type="submit" id="upload_save" class="btn btn-success"> Save And Next >></button>
</form>
JS:
$('#upload_save').click(function(){
event.preventDefault();
$.ajax({
url: 'controller.php',
type: 'post',
dataType: 'json',
data: new FormData($(this).parents('form')),
processData: false,
contentType: false,
success: function(suc){
alert(suc['msg']);
},
error: function(error){
alert(error);
}
});
});
controller.php:
$reason = $_POST['reason'];
var_dump($_FILES);
if ($reason === "step17" ) {
var_dump($_FILES);
$status=array();
$uploaded_file=array();
$document_type=array("Photo","Aadhar");
$i=0;
$j=0;
foreach($_FILES as $key=>$file)
{
$status= uploadImage($key, $file_size=5000000, "../..".FILE_PATH_LOC );
if($status['error']!==200 && $status['status']===false )
{
echo json_encode(array('status'=>'false','msg'=>"Error ".$file['name']." ".$status['msg']));
break;
}
}
}
Output of var_dump($_FILES):
array(0){
}
The issue I'm facing here is that the data I post is not being recognized in controller.php and control doesn't reach inside the if condition.
You need to make stuphoto as an array. Sor please try to change this line
<td><br><input id="file-upload" name="stuphoto" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
To
<td><br><input id="file-upload" name="stuphoto[]" type="file" accept=".JPG" class="custom-file-upload" style="display: inline;"></td>
and
foreach($_FILES as $key=>$file)
to
foreach($_FILES['stuphoto']['name'] as $key=>$file)
Your problem is that you are passing a jQuery object as the parameter to the FormData constructor when it takes an html form
$('#upload_save').click(function(event){
event.preventDefault();
$.ajax({
url: 'controller.php',
type: 'post',
dataType: 'json',
data: new FormData(this.form), // pass the form itself to the constructor
processData: false,
contentType: false,
success: function(suc){
alert(suc['msg']);
},
error: function(error){
alert(error);
}
});
});
I have an upload mechanism which looks like that in the View:
<div method="post" enctype="multipart/form-data">
<input type="hidden" id="ProjectId" name="ProjectId" value="#Model.ProjectId"/>
<input type="hidden" id="Name" name="Name" value= "" />
<input type="hidden" id="Id" name="Id" value="" />
<div class="col-md-10">
<div class="form-group">
<input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
<input type="submit" value="Upload" id="UploadInputFileButton" onclick="UploadInstallIntructions();"/>
</div>
</div>
</div>
This is my uploadinstructions() method, which gets called when the user pushes the 'Upload'button.
script>
function UploadInstallIntructions() {
var name = document.getElementById('SoftwareVersionName').value;
var id = document.getElementById("Id").value;
var iFormFile = document.getElementById("ChooseInputFile").files[0];
$.ajax({
type: "POST",
url: '#Url.Action("UploadInputFile", "SoftwareVersion")',
data: { projectId: #Model.ProjectId, Name: name, Id: id, inputFile: iFormFile},
cache: false,
success: function (response) {
window.location.href = response;
}
});
return data;
}
</script>
So this is a simple ajax call that calls a method on my controller with the specified arguments. My problem is that the last argument which should be the file data, of IFormFile type, so that I can work with it in my controller, doesn't get set. Is there a better way I can bind my IFormFile object in my view? Normally just the line :
input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
should have worked to bind the IFormFile.
Edit: Not a duplicate of how to append whole set of model to formdata and obtain it in MVC, because my question was not about binding with FormData, but IFormFile not automattically getting created from the View.
Once i have done upload a image file like this..
$('input[type="file"]').ajaxfileupload({
'action': 'uploadFile.jsp',
'cache': false,
'onComplete': function(response) {
$('#upload').hide();
BootstrapDialog.show({
title: 'Alert!',
message: 'Image Upload Successfully',
buttons: [{
label: 'Ok',
action: function(dialog) {
dialog.close();
}
}]
});
var img_src = "../profilepic/" + response;
setTimeout(5000);
$("#image").attr("src", img_src);
},
'onStart': function() {
$('#upload').show();
}
});
<input type="file" name="datafile" accept="image/*"/><br/>
<div id="upload" style="display:none;">Uploading..</div>
If you wish to upload files like this, visit this link for
jQuery.AjaxFileUpload.js
Try below code:
<form name="UpdateInstall" id="UpdateInstall" method="post" enctype="multipart/form-data">
<input type="hidden" id="ProjectId" name="ProjectId" value="#Model.ProjectId"/>
<input type="hidden" id="Name" name="Name" value= "" />
<input type="hidden" id="Id" name="Id" value="" />
<div class="col-md-10">
<div class="form-group">
<input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
<input type="submit" value="Upload" id="UploadInputFileButton" onclick="UploadInstallIntructions();"/>
</div>
</div>
</form>
<script>
function UploadInstallIntructions() {
var formData = new FormData($("#UpdateInstall")[0]);
$.ajax({
type: "POST",
url: '#Url.Action("UploadInputFile", "SoftwareVersion")',
data: formData,
processData: false,
contentType: false,
success: function (response) {
window.location.href = response;
}
});
return data;
}
</script>
I'm facing error on Upload xml and upload csv am a rookie so please can you provide me a elaborate answer
I've tried debugging the code on clicking upload button till upload function is working fine on jumping to uploadxml() function the data is not sent.
My HTML code
<div class="file-upload">
<form id="file-upload-form">
<div class="upload">
<div class="col-lg-6">
<div class="input-group" id="one">
<input type="text" class="form-control" id="t1" placeholder="Select an xml file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="xmlbtn">Browse</button>
</span>
</div>
<input type="file" accept=".xml" class="hidden" id="xmlPicker" name="xmlFile"/>
</div>
<div class="col-lg-6">
<div class="input-group" id="two">
<input type="text" class="form-control" id="t2" placeholder="Select an csv file.." >
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="csvbtn">Browse</button>
</span>
</div>
<input type="file" class="hidden" accept=".csv" id="csvPicker" name="csvFile"/>
</div>
</div>
<div class="uploadfooter">
<button class="btn btn-default center" type="button" id="upload">Upload</button>
</div>
</form>
</div>
My Js
$(document).ready(function () {
$(".ts-sidebar-menu li a").each(function () {
if ($(this).next().length > 0) {
$(this).addClass("parent");
};
})
var menux = $('.ts-sidebar-menu li a.parent');
$('<div class="more"><i class="fa fa-angle-down"></i></div>').insertBefore(menux);
$('.more').click(function () {
$(this).parent('li').toggleClass('open');
});
$('.parent').click(function (e) {
e.preventDefault();
$(this).parent('li').toggleClass('open');
});
$('.menu-btn').click(function () {
$('nav.ts-sidebar').toggleClass('menu-open');
});
$('#zctb').DataTable();
$("#input-43").fileinput({
showPreview: false,
allowedFileExtensions: ["zip", "rar", "gz", "tgz"],
elErrorContainer: "#errorBlock43"
// you can configure `msgErrorClass` and `msgInvalidFileExtension` as well
});
$("#xmlbtn").bind("click", function(){
$("#xmlPicker").trigger("click");
});
$("#xmlPicker").bind("change", function(e){
$("#t1").val($("#xmlPicker")[0].files[0].name);
})
$("#csvbtn").bind("click", function () {
$("#csvPicker").trigger("click");
});
$("#csvPicker").bind("change", function (e) {
$("#t2").val($("#csvPicker")[0].files[0].name)
})
$("#upload").on("click",function () {
var firstfile = $("#t1").val();
var secondfile = $("#t2").val();
if(!firstfile || firstfile != null){
updateXml();
}
if(!secondfile || secondfile != null){
updatecsv();
}
})
function updateXml(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
function updatecsv(){
var form = $("#file-upload-form").val()
var data = new FormData(form);
$.ajax({
url: "/update",
data: data,
type: "put",
contentType: false,
processData: false,
cache: false,
success: function (response) {
console.log(response);
}
})
}
});
This line here:
var form = $("#file-upload-form").val()
A form does not have a value, its inputs have one. FormData expects a form, so you need to give it a reference to it.
var form = $("#file-upload-form");
var data = new FormData(form[0]); //expects a DOM form
I'm trying to upload a file via ajax together with some fields in a form. However, it doesn't work. I get this error.
Undefined Index :- File
Here's my code.
HTML
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
Ajax
$("#add_product").click(function(e) {
e.preventDefault();
product_name = $("product_name").val();
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: $("#add_new_product").serialize(),
success: function(response) {
//
alert(response);
}
})
});
PHP
if (0 < $_FILES['file']['error']) {
echo ":!";
} else {
echo "ASa";
}
What am I missing here?
Can you try using FormData():
$("form#files").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The above is a sample code, but you may use it to modify it.
you can use FormData
$("#add_product").click(function(e) {
e.preventDefault();
var fdata = new FormData()
fdata.append("product_name", $("product_name").val());
if ($("#file")[0].files.length > 0)
fdata.append("file", $("#file")[0].files[0])
//d = $("#add_new_product").serialize();
$.ajax({
type: 'POST',
url: 'ajax.php',
data: fdata,
contentType: false,
processData: false,
success: function(response) {
//
alert(response);
}
})
});
<!-- File Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="file">Upload Software / File</label>
<div class="col-md-4">
<input id="file" name="file" class="input-file" type="file">
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label" for="price">Price($)</label>
<div class="col-md-4">
<input id="price" name="price" type="text" placeholder="Price" class="form-control input-md" required="">
</div>
</div>
We need to acknowledge first is that we need to APPEND both Form Input Data and Form File(s) into a single FormData variable.
Here is my solution in which I have enabled Multi File option so that this solution can fit for all examples.
It is Important to include name attribute in the input controls to make it work properly on server side in most of cases. If you are using C# then you can use simply Request.Form["nameAttribute"] to simply get the function. It is similar for Java and other languages.
My Sample Code is
$(document).ready(function () //Setting up on Document to Ready Function
{
$("#btnUpload").click(function (event) {
//getting form into Jquery Wrapper Instance to enable JQuery Functions on form
var form = $("#myForm1");
//Serializing all For Input Values (not files!) in an Array Collection so that we can iterate this collection later.
var params = form.serializeArray();
//Getting Files Collection
var files = $("#File1")[0].files;
//Declaring new Form Data Instance
var formData = new FormData();
//Looping through uploaded files collection in case there is a Multi File Upload. This also works for single i.e simply remove MULTIPLE attribute from file control in HTML.
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
//Now Looping the parameters for all form input fields and assigning them as Name Value pairs.
$(params).each(function (index, element) {
formData.append(element.name, element.value);
});
//disabling Submit Button so that user cannot press Submit Multiple times
var btn = $(this);
btn.val("Uploading...");
btn.prop("disabled", true);
$.ajax({
url: "Handler.ashx", //You can replace this with MVC/WebAPI/PHP/Java etc
method: "post",
data: formData,
contentType: false,
processData: false,
success: function () {
//Firing event if File Upload is completed!
alert("Upload Completed");
btn.prop("disabled", false);
btn.val("Submit");
$("#File1").val("");
},
error: function (error) { alert("Error"); }
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" id="myForm1">
<p><textarea id="TextArea1" rows="2" cols="20" name="TextArea1"></textarea></p>
<p><input id="File1" type="file" multiple="multiple" /></p>
<input id="btnUpload" type="button" value="Submit" />
</form>
For a working example (asp.net C# with handlers) you can visit sample code on https://github.com/vibs2006/HttpFileHandlerFormDataSample
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:
Here's the form :
<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-4" for="societe">Company</label>
<div class="col-md-8">
<input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
<div class="col-md-8">
<textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
</div>
</div>
<div class="form-group" id="input_file">
<label class="control-label col-md-4" for="image_input_field">Logo</label>
<div class="col-md-8">
<div class="input-group uploaddiv">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Parcourir <input type="file" id="image_input_field" name="file">
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="form-actions col-md-9 col-md-offset-3 text-right">
<input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
<input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
</div>
</div>
</fieldset>
</form>
I can't seem to find what's the error in my code ! Here's the AJAX call :
jQuery(document).on("click", "#submit", function(e) {
e.preventDefault();
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
jQuery.ajax({
url: "ajax.php",
type: "post",
data: {
'file': file,
'module' : 'ajax_data_form',
'societe': societe,
'message': message
},
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// jQuery('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
});
And here's the ajax.php:
<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
var_dump($_FILES);
}
$.ajax({
type: "POST",
url: pathname,
data: new FormData($('#devis')[0]),
processData: false,
contentType: false,
success: function (data) {
$("#divider").html(data);
}
});
and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.
can you try it
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "file="+file,
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// $('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
}); });
</script>
In ajax.php
just write
echo 'something';
As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.
You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).
Here is the link:
https://github.com/dogzworld/iframe-post-form
Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."
As mentioned you can send response from the server and display updates on your webpage accordingly.
There has to be a demo page but it is not working as of now.
You can also use it for file uploads.
Calling Example:
jQuery('#frmId').iframePostForm({
json : true,
post : function () {
//return true or false
return true;
},
complete : function (response) {
//complete event
console.log(response);
}
});
Using a Jquery Plugin Called Jquery Form plugin Link
I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.
$("#devis").ajaxSubmit(options);
return false;
The you can easily get the file in the php page like this
$ImageTempname = $_FILES['ImageFile']['tmp_name'];
$ImageFilename = $_FILES['ImageFile']['name'];
$ImageType = $_FILES['ImageFile']['type'];
and so on.....