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);
}
});
});
Related
I have a case as follow:
Step 1: Open pop-up, upload file -> Success.
Step 2: Edit file just uploaded.
Step 3: without reload website, reopen pop-up.
Step 4: select file just edited to upload.
Expected result: Upload success.
Actual result : upload error: Data format of the uploaded file is not EXCEL file.
How i can fix it??
This is my code
Code js
function handlerUploadFile() {
var form = $(‘'#uploadFile_action')[#];
var data = new FormData(form);
loading_ajax();
$.ajax({
type: "POST",
enctype: 'multipart / form - data ',
url: '../sac0#12/uploadFile.action',
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 620000,
success: function(data, status, xhr) {
close_loading_ajax(
};
var messageld = "";
var ct = xhr.getResponseHeader('content - type ') || °";
if (ct.indexOf('html') > -1) {
showNotifyDialog("fileNotFormatExcel");
return; +
if (ct.indexOf('json') > -1) {
var obj = JSON.parse(data);
if (obj.result == "SUCCESS”) {
showNotifyDialog("fileUploadSuccess") $("#myModalUpload”).css("
display”, “none ")};
$('#itemDetails')
}.empty(); loadContent(limit, offset, transactionId, scrollTop);
}
else {
if (obj.code == "EA-0003") {
messageId = "EA-0003";
contentConfirm = mesSystem[messageId];
alert(contentConfirm);
} else if (obj.code == "ERROR_PLT_ID_LENGTH") {
messageId = "ERROR_PLT_ID_LENGTH";
contentConfirm = mesSystem[messageId];
alert(contentConfirm);
} else {
alert("Data format of the uploaded file is not correct.");
}
}
}
},
error: function(e) {
close_loading_ajax();
alert("Data format of the uploaded file is not EXCEL file.");
}
});
}
code jsp
<form id="uploadFile_action" name="uploadFile_action" method="post" enctype="multipart/form-data">
<div class="row" style="margin: 5px 0 0; border-bottom: 1px solid gray; height: 40px;">
<div class="col-md-12">
<div class="col-md-2 col-sm-2 col-xs-2 file" style="margin-top: 5px; width: auto;">
<b style="font-weight: 900;">Upload File:</b>
</div>
<div class="col-md-9 col-xs-9 col-sm-9 file-return" contentEditable=false data-text="File path"></div>
<div class="col-md-1 col-xs-1 col-sm-1 input-file-container">
<input type="hidden" name="confirm" value="false" id="uploadFile_action_confirm" />
<input type="file" name="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" class="input-file" value="" id="uploadFile_action_file" />
<button tabindex="0" for="my-file" class="input-file-trigger" value="Browse"><b style="font-weight: 800;">Browse</b></button>
</div>
</div>
<div class="col-md-12">
<p id="emptyFileUpload" style="display: none;"></p>
</div>
</div>
<div class="row">
<input type="submit" name="upload" class="btn btn-primary btn-danger textWhite" id="uploadFile_action_0" style="height: 34px" value="Upload" />
<input type="button" value="Back" class="cancelButton">
</div>
<s:hidden name="transactionId"></s:hidden>
</form>
I'am trying to send an id in my url but my controller doesn't get that value
$("#ChangeSlideForm").on("submit", function(){
$.ajax({
type: "POST",
url: base_url + "Visualiser/ChangeSlide/21",
success: function (response) {
alert(response);
// $("#deleteConfirm").modal('hide');
// jQuery(function RefreshPageAdd($){
// $('#deleteConfirm').on('hidden.bs.modal', function (e) {
// location.reload();
// });
// });
}
});
});
My View
<div id="bodyChange" class="modal-body">
<form id = "ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<label class="btnSlide btn btn-outline-success">
Zip <input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success">
Csv <input class="file" name ="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</form>
My controller header :
public function ChangeSlide($id){
print_r($id);
}
When I a put the id in the url directly then the parameter is accessible otherwise when I pass with ajax, It doesn't detect the parameter.
Try this:-
The HTML
<form id="ChangeSlideForm" action="<?php echo base_url() ?>Visualiser/ChangeSlide/21" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<div id="bodyChange" class="modal-body">
<label class="btnSlide btn btn-outline-success"> Zip
<input class="file" name="file[]" type="file" hidden>
</label>
<label class="btnSlide btn btn-outline-success"> Csv
<input class="file" name="file[]" type="file" hidden>
</label>
</div>
<div class="modal-footer">
<div class="col-md-12 text-center">
<button type="submit" class="btn btn-primary col-md-6">Ajouter</button>
</div>
</div>
</form>
The Script:
<script type="text/javascript">
$(document).ready(function(){
$("#ChangeSlideForm").on("submit", function(e){
e.preventDefault();
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
data : $(this).serializeArray(),
success : function(data)
{
console.log(data)
},
error: function (xhr)
{
console.log(xhr)
}
});
});
})
</script>
Try this
public function ChangeSlide(){
print_r($this->uri->segment(3));
}
You missing parameter data in $.ajax(). So your ajax didn't send any data to your controller
When you pass value with ajax then controller method get that value as $this->input->post('id'); not as parameter.
So you have to add following to method
public function ChangeSlide($id = "")
{
}
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 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.
I have created a form to upload two files - questionpaper and the key. But the Ajax request is not working in an intended manner. I have been trying and trying but unable to figure out the bug. Please help.
Here is my form.
<form name="facform" id="facform" data-abide="ajax" enctype="multipart/form-data">
<fieldset>
<legend> All fields are required </legend>
<div class="row">
<div class="large-3 medium-3 columns">
<label> <b> Upload Question Paper </b> </label>
<input type="file" id="qfile" name="qfile" tabindex="7" required>
</div>
<div class="large-3 medium-3 columns end">
<label><b> Upload Key </b></label>
<input type="file" id="kfile" name="kfile" tabindex="8" required>
</div>
</div>
</fieldset>
<div class="row">
<div class="large-6 medium-6 columns">
<label><img id="loadingimg" src="http://dev.cloudcell.co.uk/bin/loading.gif"/></label>
<input id="form-submit" type="submit" class="button tiny" value="Submit" />
</div>
</div>
</form>
Here goes the javascript part.
<script>
//-----------------------//
$('#facform').on('valid.fndtn.abide', function() {
var fileInput = document.getElementById('facform');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('qfile', file);
formData.append('kfile', file);
var form_url = 'getfiles.php';
$("#form-submit").hide();
$("#loadingimg").show();
$.ajax({
url: form_url,
type: 'POST',
data: formdata,
processData: false,
cache: false,
success: function(returnhtml){
$("#loadingimg").hide();
$("#facform").hide();
$("#smsg").html(returnhtml);
$("#facform")[0].reset();
}
//-----------------------//
});
});
</script>
to upload files using Ajax or jQuery , you need to use hidden iframe
this is full example for ajaxfileupload.js class allow you to use upload form .
or you could create simple function to submit your form into hidden iframe then get the iframe body html or text using jQuery as response .
<html>
<head>
<link href="http://www.phpletter.com/css/general.css" rel="stylesheet" type="text/css" media="screen">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="http://www.phpletter.com/contents/ajaxfileupload/ajaxfileupload.js"></script>
<script type="text/javascript">
function ajaxFileUpload()
{
$.ajaxFileUpload
(
{
//YOUR URL TO RECEIVE THE FILE
url: 'http://localhost/testing/postfile.php',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
},
error: function (data, status, e)
{
alert(data.error);
alert(e);
}
}
)
return false;
}
</script>
</head>
<body>
<form name="form" action="" method="POST" enctype="multipart/form-data">
<table cellpadding="0" cellspacing="0" class="tableForm">
<thead>
<tr>
<th>Ajax File Upload</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="fileToUpload" type="file" size="45" name="fileToUpload" class="input"></td>
</tr>
<tr>
<td>Please select a file and click Upload button</td>
</tr>
</tbody>
<tfoot>
<tr>
<td><button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">Upload</button></td>
</tr>
</tfoot>
</table>
</form>
</body>
</html>