Drag and Drop Zone opening file instead of uploading to server - php

I have a file upload zone, one that let's you choose the file while the other is a drag and drop file upload zone.
Choosing file and clicking submit works perfectly fine.
The drag and drop zone however opens/downloads the file instead of uploading.
I think my PHP code is correct, because the file is getting correctly uploaded to server on choosing and uploading.
This is the JQuery code where I think there's a possible error.
+ function($) {
'use strict';
// UPLOAD CLASS DEFINITION
// ======================
var dropZone = document.getElementById('drop-zone');
var uploadForm = document.getElementById('js-upload-form');
var startUpload = function(files) {
console.log(files)
}
uploadForm.addEventListener('submit', function(e) {
var uploadFiles = document.getElementById('js-upload-files').files;
e.preventDefault()
startUpload(uploadFiles)
})
dropZone.ondrop = function(e) {
e.preventDefault();
this.className = 'upload-drop-zone';
startUpload(e.dataTransfer.items)
}
dropZone.ondragover = function() {
this.className = 'upload-drop-zone drop';
return false;
}
dropZone.ondragleave = function() {
this.className = 'upload-drop-zone';
return false;
}
}(jQuery);
Here's the HTML for a better reference:
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><strong>Upload CSV File</strong> <small>Insert Leads to MongoDB</small></div>
<div class="panel-body">
<!-- Standard Form -->
<h4>Select files from your computer</h4>
<form action="" method="post" enctype="multipart/form-data" id="js-upload-form">
<div class="form-inline">
<div class="form-group">
<input type="file" name="file" id="js-upload-files">
</div>
<button type="submit" class="btn btn-sm btn-primary" id="js-upload-submit">Upload files</button>
</div>
</form>
<!-- Drop Zone -->
<h4>Or drag and drop files below</h4>
<div class="upload-drop-zone" id="drop-zone">
Just drag and drop files here
</div>
</div>
</div>
I want the drag and drop zone to upload the file to server as well instead of opening.

Related

$_FILES is empty when drop a file but not with click

My JQuery populates $_FILES only when click on input type file but not when drop in a file.
All the examples, tutorials, documentation I have found is about using Ajax or pure JavaScript. None is what I want to do. I have found also plently of plugins, libraries, ... I just want to be able to drop a file.....
The FORM:
<form id="item-form" role="form" method="post" enctype="multipart/form-data">
<div id="image-holder" class="dropBox">
<img src="" style="width: 100%; padding: 10px;display: none;">
</div>
<div id="fileBox">
<input type="file" name="image_file_input" id="image_file_input" />
</div>
<button type="submit" name="submit">SAVE</button>
</form>
The JQUERY:
$(".dropBox").on("drop", function(e) {
e.preventDefault();
e.stopPropagation();
runUpload( e.originalEvent.dataTransfer.files[0] );
});
$(".dropBox").click(function(){
$("#image_file_input").click();
});
$('input[type=file]').on('change', function(){
runUpload( this.files[0] );
});
function runUpload( file ) {
var reader = new FileReader(), image = new Image();
reader.readAsDataURL( file );
reader.onload = function( file ) {
var image_holder = $("#image-holder");
image_holder.empty();
$("<img />", {
"src": file.target.result,
"class": ""
}).appendTo(image_holder);
$("#dropBox").hide();
$(image_holder).show();
}
The PHP:
if ( !empty($_FILES) ) {
echo '---> Files not empty ';
}else{
echo '---> Files empty ';
}
I don't want to use Ajax. I'm only showing the relevant part of the code to concentrate in the issue.
If I click on the dropBox or I drop a file (image) into the dropBox element I can see the image selected in the image_holder div.
When the form is submited if the file is from a click event it works perfectly but when is from a drop event $_FILES is empty.
I'm convinced the problem is what I pass to the runUpload function when dropping. I have tried all sort of things but unable to see what is wrong.

PHP and Ajax Upload file path to Mysql and save renamed image to the folder fails

I am trying to upload the file path and other parameters to mysql and I keept the file to the folder with Ajax and PHP it fails, For String parameters it's ok, but get file parameter to database I get empty file data.
an error: Uncaught TypeError: Illegal invocation
HTML form :
................
<form role="form" action=""
method="post" autocomplete="off" class="form"
enctype="multipart/form-data" >
<div class="form-group">
<label class="" for="">Ministry in the
church(facultative)</label>
<input type="text" name="mn_church" placeholder="Facultative" class="form-control" id="mn_church">
</div>
</fieldset>
<!-- end -->
<!-- Attachements -->
<fieldset>
<h4>Document attachments:</h4><br>
<div class="form-group">
<label class="" for="">Last degree obtained</label>
<input type="file" name="ldgree" placeholder="Upload" class=" form-control" id="ldgree">
</div>
<button type="button" class="btn btn-previous">Previous</button>
<button type="button" onclick="insertDataThirdStep() " class="btn btn-next">Next</button>
</div>
</fieldset>
.............
PHP code :
------------------
$mn_church = trim($_POST['mn_church']);
$mn_church = strip_tags($mn_church);
$mn_church = htmlspecialchars($mn_church);
// upload file
$ldgree = $_FILES['ldgree']['name'];
$tmpName = $_FILES['ldgree']['tmp_name'];
// Rename image with a random number
$random_digit=rand(0000,9999);
$renamed_image=$random_digit.$ldgree;
//upload renamed image and image path to db variable
$filePath = $uploadDir . $renamed_image;
//upload renamed image and path image to the folder
$result = move_uploaded_file($tmpName, $filePath);
if(!get_magic_quotes_gpc())
{
// $fileName = addslashes($fileName);
// Add slashes between folder and image
$filePath = addslashes($filePath);
}
// end first file
//start student application by inserting the form's data to database
$query = "
UPDATE
aku_student_application
SET
mychurch ='$mn_church',
last_degree_optained='$filePath ',
"
-------------------
Jquery code with ajax I used to work with php in order to avoid page reload :
var mn_church=$("#mn_church").val();
// Attachment
var ldgree = $('#ldgree').prop('files')[0];
$.ajax({
url:'step-4-appli-form-attachments.php',
method:'POST',
data:{
mn_church:mn_church,
ldgree:ldgree
},
success:function(response){
// alert(response);
console.log('Success fourth step');
}
With this solution you can upload more than one file's path to mysql and and photos to folders using one form, the trick I used is FormData to upload file and String(text) too.
First Id did I gave my form id then I referenced Id in Jquery file in order to use it in form data.
HTML Code:
................
<form role="form" action=""
method="post" autocomplete="off" class="form"
enctype="multipart/form-data" id="myform" >
<div class="form-group">
<label class="" for="">Ministry in the
church(facultative)</label>
<input type="text" name="mn_church" placeholder="Facultative" class="form-control" id="mn_church">
</div>
</fieldset>
<!-- end -->
<!-- Attachements -->
<fieldset>
<h4>Document attachments:</h4><br>
<div class="form-group">
<label class="" for="">Last degree obtained</label>
<input type="file" name="ldgree" placeholder="Upload" class=" form-control" id="ldgree">
</div>
<button type="button" class="btn btn-previous">Previous</button>
<button type="button" onclick="insertDataThirdStep() " class="btn btn-next">Next</button>
</div>
</fieldset>
.............
I reformated my php code like this :
$mn_church = trim($_POST['mn_church']);
$mn_church = strip_tags($mn_church);
$mn_church = htmlspecialchars($mn_church);
$fileName = rand(0000,9999).'_'.$_FILES['ldgree']['name'];
$sourcePath = $_FILES['ldgree']['tmp_name'];
$targetPath = "images/fuploads/".$fileName;
if(move_uploaded_file($sourcePath,$targetPath)){
$uploadedFile = $fileName;
}
$query = "
UPDATE
aku_student_application
SET
mychurch ='$mn_church',
last_degree_optained='$targetPath' "
Jquery code to work with php
function insertDataFourthStep() {
var form = document.getElementById('myform');
var church _Input = document.getElementById('mn_church');
var Lastdgree_Input = document.getElementById('ldgree').files[0];
var mn_church= new FormData(form);
var ldgree = new FormData(form);
student_id.append("mn_church",church _Input);
ldgree.append("file",Lastdgree_Input);
$.ajax({
type: 'POST',
url: 'step-4-appli-form-attachments.php',
data:ldgree,mn_church,
contentType: false,
cache: false,
processData:false,
success: function(data){
console.log('Success fourth step');
// clear file field
// $("#ldgree").val("");
}
});
}
Thank you friends for your positive comments

I want to handle dynamic inputs in a form using jQuery and PHP. I'm able to add and delete input fields but failed to store them

these are the javascript functions i'm using
function addFac() {
$("<div>").load("includes/facility.php", function() {
$("#fac").append($(this).html());
});
}
function deleteFac() {
$('div.facility-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
here is the HTML code:
<div class="facility-item well" style="clear:both;">
<div class="row">
<div class="col-lg-1 col-sm-1 col-xs-3 padder-col">
<input type="checkbox" class="chk-lg">
</div>
<div class="col-lg-10 col-lg-offset-1 col-md-9 col-md-offset-2 col-sm-11 col-xs-9">
<input class="form-control" type="text" placeholder="Describe facility" name="faci[]" >
</div>
</div>
</div>
This code of html is written in a file named facilities.php and the file is included into the index.php. This is how i'm able to add and remove the dynamic input fields. But
when I wrote the PHP file:
$facilities = "0";
$faci = $_POST["faci"];
var_dump($faci);
even after having multiple facilities, it showed only one value in array.
Here is the working code Paste and run.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_button'); //Add button selector
var wrapper = $('.field_wrapper'); //Input field wrapper
var fieldHTML = '<div><input type="text" name="field_name[]" value=""/><img src="remove-icon.png"/>remove</div>'; //New input field html
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
</script>
<form name="karan" action="" method="post">
<div class="field_wrapper">
<div>
<input type="text" name="field_name[]" value="">
add
</div>
</div>
<input type="submit" name="submit" value="SUBMIT">
</form>
<?php
print '<pre>';
print_r($_REQUEST['field_name']);
print '</pre>';
//output
?>
<?php
$field_values_array = $_REQUEST['field_name'];
foreach($field_values_array as $value){
//your database query goes here
}
?>

Cant make my upload form work using 2 versions of jQuery despite jQuery.noConflict()

I have one webpage that has 2 different forms in it, the 1st one is for uploading pictures (and it's supposed to give the link of the freshly uploaded images), and the second one is a "regular" form that allows to add a product to the database, in which I use the links given by the 1st form. The problem is that I use bootstrap's jQuery, and the upload form uses the 1.7.2 version (no need to say, there are conflicts.)
Once I hit the "send" button, it's supposed to make a loading bar appear and show "100%", followed by the image URL, while the upload process is done in another file named 'upload.php'
The problem is, even though I used 'jQuery.noConflic();' it still continues to redirect me to upload.php where there's nothing to see, but I can't find the problem...
Here's the upload form :
<form id="myForm" action="upload.php" name="upload" method="post" enctype="multipart/form-data">
<div class="form-group">
<label class="col-md-4 control-label" for="filebutton">Uploader une image</label>
<div class="col-md-3">
<input id="filebutton" name="filebutton" class="input-file" type="file">
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
<br />
<div id="alerte"></div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" for="envoyer"></label>
<div class="col-md-3">
<button type="file" value="envoyer" id="formenvoyer" name="myfile" class="btn btn-primary">Envoyer</button>
</div>
</div>
</div>
</form>
Here is the PHP file :
<?php
$output_dir = "img/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
echo "<p>Uploaded File :<br />http://grindhouseleather.esy.es/admin/img/".$_FILES["myfile"]["name"]."</p>";
}
}
?>
And here's the JS :
jQuery = jQuery.noConflict();
jQuery(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#alerte").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#alerte").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#alerte").html("<font color='red'> ERROR: Impossible d'uploader les fichiers</font>");
}
};
$("#myForm").ajaxForm(options);
});
What did I miss ?
Thank you in advance !
You shouldn't use jQuery for jQuery.noConflict();. Change it to:
jq = jQuery.noConflict();
The reason is:
jQuery = jQuery.noConflict();
The above code makes no difference.

Upload on iframe in modal

I have a modal containing a form and an iframe.
The form has a file field and post to the iframe.
The php controller return the uniqid (basically the name) of the uploaded file.
The upload works well and my iframe contains the uniqid.
I would like to display this uniqid on my main page.
My issue is that I don't know how to wait the end of the upload to show the uniqid.
The form and iframe :
<form id="uploadForm" enctype="multipart/form-data" action="{{ path('lesson_upload') }}" target="uploadFrame" method="post">
<label for="uploadFile">Document :</label>
<input id="uploadFile" name="uploadFile" type="file" />
<br /><br />
<input class="btn btn-primary" id="uploadSubmit" type="submit" value="Upload" />
</form>
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe hidden id="uploadFrame" name="uploadFrame"></iframe>
</div>
The JavaScript to fill the modal with the form :
$(document).on('click', '#computer-upload', function ()
{
var url = Routing.generate('lesson_upload_computer');
$.get(url, function (data)
{
$('#modal-various .modal-body').html(data);
return false;
});
return false;
});
The iframe at the end of an upload :
<div id="uploadInfos">
<div id="uploadStatus">Aucun upload en cours</div>
<iframe hidden="" id="uploadFrame" name="uploadFrame">
#document
<html>
<body>
<body>533ebac647b7e</body>
</body>
</html>
</iframe>
</div>
Does anyone have an idea ?
Thanks !
If you don't use an AJAX upload, after a little research, you cannot add an event that detects when the upload has finished.
You now have 2 options:
Fetch the id from the iframe every ~100ms and if it is not empty or null, the id will be in:
document.checkForId = function() {
id = $('#uploadFrame').contents().find('#idInIframeDivOrOtherContainer');
if (id) {
window.clearInterval(intervalId);
}
};
$(document).ready(function() {
intervalId = window.setInterval('document.checkForId', 100);
});
When posting data, return javascript that sets the id in the main page (if you have jquery in the iframe):
<script>
$(document).ready(function() {
$('#divInParentWindow', parent.document).text('<?php echo $id; ?>');
});
</script>
If your iFrame has its source on the same server/domain level as your main page. You could simply define a function at your main page
function iframeHasLoaded() {
var body = document.getElementById('uploadFrame').contentWindow.document.body.innerHTML;
}
And, from your iFrame
window.onload=function() { parent.iframeHasLoaded() };
This should work.

Categories