Dragstart event does not fire in firefox - javascript

I have a problem with a dragstart event in my javascript. When using chrome it works perfectly fine, but not in firefox, where it wont fire at all.
(function () {
var dropzone = document.getElementById('dropzone-add');
var dropzone2 = document.getElementById('dropzone-del');
var draggedItem;
function drag (e) { //This one does not fire in firefox.. I have tried many methods..
e.dataTransfer.setData('text/plain', e.target.src);
draggedItem = e.target;
}
var displayUploads = function (data) {
var uploads = document.getElementById('uploads');
for(index=0; index<data.length; index=index+1){
var div = document.createElement('div');
var anchor = document.createElement('a');
var image = document.createElement('img');
div.className = 'col-lg-2 col-md-4 col-xs-6 thumb';
anchor.className = 'thumbnail';
anchor.href = '#';
image.className = 'img-responsive';
image.src = data[index].file;
image.alt = data[index].name;
anchor.appendChild(image);
div.appendChild(anchor);
uploads.insertBefore(div, uploads.firstChild);
image.setAttribute('draggable', true);
image.ondragstart = function(event) {drag(event)}; //This is the elment that will be draggable.
//image.addEventListener('dragstart', drag, false);
}
}
var upload = function (files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
index;
for(index=0; index<files.length; index = index+1){
formData.append('file[]', files[index]);
}
xhr.onload = function () {
var data = JSON.parse(this.responseText);
displayUploads(data);
}
xhr.open('post', 'upload.php');
xhr.send(formData);
}
var removeFile = function(src){
xhr = new XMLHttpRequest();
xhr.onload = function () {
var data = this.responseText;
console.log(data);
}
xhr.open('post', 'delete.php');
xhr.send(src);
}
dropzone.ondrop = function (e) {
e.preventDefault();
this.className = 'dropzone';
if(e.dataTransfer.files.length < 1){
alert('Use the other dropzone to delete.');
return false;
}
else
upload(e.dataTransfer.files);
}
dropzone.ondragover = function () {
this.className = 'dropzone dragover';
return false;
}
dropzone.ondragleave = function () {
this.className = 'dropzone';
return false;
}
dropzone2.ondrop = function (e) {
e.preventDefault();
this.className = 'dropzone';
var data = e.dataTransfer.getData('text');
console.log(draggedItem);
console.log(data);
//removeFile(data);
}
dropzone2.ondragover = function () {
this.className = 'dropzone dragover';
return false;
}
}());
The outputed images becomes properly draggable and is working fine in chrome. I have tried to use methods like event.originalEvent without success. Would appreciate any help, I am stuck right now. Please ignore the awfulness in the loop.
On top html
<html>
<head>
<meta charset="utf-8">
<title>Upload - drag drop</title>
<link rel="stylesheet" href="global.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div class="content-fluid">
<div class="dropzone" id="dropzone-add">Drag the file you want to upload here</div>
<div class="dropzone" id="dropzone-del">Drag the file you want to delete here</div>
<div class="row" id="uploads">
</div>
</div>
Upload.php
<?php
$uploaded = array();
if(!empty($_FILES['file']['name'][0])){
$upload_folder = 'uploads/';
foreach($_FILES['file']['name'] as $position => $name){
$upload_path = $upload_folder . time() . '_' . basename($_FILES['file']['name'][$position]);
if(move_uploaded_file($_FILES['file']['tmp_name'][$position], $upload_path)){
$uploaded[] = array('name' => $name, 'file' => $upload_path);
}
}
echo json_encode($uploaded);
}
?>

Related

First time making my drag and drop FileReader() event but can't read the content of the file

Hi I need help on how I can make my drag and drop read the .text files that is dropped in the dropzone.. I'm still exploring javascript and would need help to guide me on what is wrong with my code..
The content of the text file should be shown on the displayarea
Reference: http://blog.teamtreehouse.com/reading-files-using-the-html5-filereader-api
Thanks in advance!
https://jsfiddle.net/d6nur0wc/1/
(function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondrop = function(event) {
event.preventDefault();
this.className = "dropzone";
console.log(event.dataTransfer.files[0]);
window.onload = function() {
var fileInput = document.getElementById('dropzone');
var fileDisplayArea = document.getElementById('displayarea');
fileInput.addEventListener('dropzone.ondrop', function(read) {
var file = fileInput.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(read) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
}
else {
fileDisplayArea.innerText = "File not supported!";
}
});
}
}
dropzone.ondragover = function() {
this.className = "dropzone dragover";
return false;
};
dropzone.ondragleave = function() {
this.className = "dropzone";
return false;
};
}())
Your code should be like this. you have to remove onload event listener. it can't be compatible here.
(function() {
var dropzone = document.getElementById("dropzone");
dropzone.ondrop = function(event) {
event.preventDefault();
this.className = "dropzone";
console.log(event.dataTransfer.files[0]);
var fileInput = document.getElementById('dropzone');
var fileDisplayArea = document.getElementById('displayarea');
var file = event.dataTransfer.files[0]
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(read) {
fileDisplayArea.innerText = reader.result;
}
reader.readAsText(file);
}
else {
fileDisplayArea.innerText = "File not supported!";
}
}
dropzone.ondragover = function() {
this.className = "dropzone dragover";
return false;
};
dropzone.ondragleave = function() {
this.className = "dropzone";
return false;
};
}())

A piece of javascript in footer.php wordpress does work on PC but not on mobile

I have the following code in my footer.php on my wordpress website
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function() {
var questionDiv = document.getElementById('question-div');
var busyDiv = document.getElementById('busy');
var resultDiv = document.getElementById('result-div');
var resultList = document.getElementById('result-list');
var xhr = new XMLHttpRequest();
var url = "https://script.google.com/macros/s/xxxxx/exec";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var result = response.result;
for (var i in result) {
var e = result[i];
if (e) {
var li = document.createElement('li');
if (e.url) {
var a = document.createElement('a');
a.href = e.url;
a.textContent = e.name;
li.appendChild(a);
} else {
li.textContent = e.name;
}
resultList.appendChild(li);
}
}
busyDiv.hidden = true;
resultDiv.hidden = false;
}
}
var form = document.getElementById('questionnaire');
var formData = new FormData(form);
var fields = ['name','email','yob','gender','xxx','yyyy'];
var params = [];
for (var i in fields) {
var field = fields[i];
params.push(field + "=" + formData.get(field));
}
xhr.send(params.join('&'));
questionDiv.hidden=true;
busyDiv.hidden=false;
return false;
};
}
</script>
This has allowed me to write and quote data from a google sheet
Now all this works on PC but it delivers 404 not found error on mobile site and the website itself is preset to be mobile responsive.
Can somebody help please?
Jane
What does your form html look like? I suspect that your mobile browser is trying to submit the form via the standard - non AJAX way and therefore is directing the browser to the url in the "action" attribute of your form. Try the following to stop this default behaviour
var myForm = document.getElementById("questionnaire");
if (myForm) {
myForm.onsubmit = function(evt) {
evt.preventDefault();

Can not convert xlsx file into json using javascript

I am trying to convert xls file into json I can convert it successfully but when I try to convert xlsx file into json I get an error as "Uncaught Header Signature: Expected d0cf11e0a1b11ae1 saw 504b030414000808".
Index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>XL to JSON</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src=" https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.js"></script>
</head>
<body>
<input type="file" id="my_file_input" />
<div id='my_file_output'></div>
<script>
var oFileIn;
$(function() {
oFileIn = document.getElementById('my_file_input');
if(oFileIn.addEventListener) {
oFileIn.addEventListener('change', filePicked, false);
}
});
function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLS.CFB.read(data, {type: 'binary'});
var wb = XLS.parse_xlscfb(cfb);
// Loop Over Each Sheet
wb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(wb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_row_object_array(wb.Sheets[sheetName]);
$("#my_file_output").html(sCSV);
console.log(oJS)
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
}
</script>
</body>
</html>
Can any one please tell me how should I solve this.I am badly stucked in this problem.Thanks in advance.
You are using the xls library which does not support xlsx files. Please use the updated one:
https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js
You can find more details and documentation for this here.
It worked with this code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JS-XLSX Live Demo</title>
<style>
#b64data
{
width:100%;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<b>JS-XLSX (XLSX/XLSB/XLSM/XLS/XML) Live Demo</b><br />
<div id="drop"></div>
<p><input type="file" name="xlfile" id="xlf" /></p>
<br />
<pre id="out"></pre>
<br />
<script src="shim.js"></script>
<script src="jszip.js"></script>
<script src="xlsx.js"></script>
<!-- uncomment the next line here and in xlsxworker.js for ODS support -->
<script src="ods.js"></script>
<script>
var X = XLSX;
var XW = {
/* worker message */
msg: 'xlsx',
/* worker scripts */
rABS: './xlsxworker2.js',
norABS: './xlsxworker1.js',
noxfer: './xlsxworker.js'
};
function fixdata(data)
{
var o = "", l = 0, w = 10240;
for(; l<data.byteLength/w; ++l) o+=String.fromCharCode.apply(null,new Uint8Array(data.slice(l*w,l*w+w)));
o+=String.fromCharCode.apply(null, new Uint8Array(data.slice(l*w)));
return o;
}
function get_radio_value( radioName )
{
var radios = document.getElementsByName( radioName );
for( var i = 0; i < radios.length; i++ )
{
if( radios[i].checked || radios.length === 1 )
{
return radios[i].value;
}
}
}
function to_json(workbook)
{
var result = {};
var result1 = [];
var array1 = [];
var arr =[];
workbook.SheetNames.forEach(function(sheetName)
{
var arr = X.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);
var array_lenght = arr.length;
for(var i = 0 ;i<array_lenght;i++ )
{
if(arr.length > 0)
{
array1 = arr[i];
result = array1;
result1.push(array1);
}
}
});
var sub_key = [];
for(var ab in result1)
{
var key = ab;
var val = result1[ab];
for(var j in val)
{
sub_key.push(j);
console.log(sub_key);
}
if((sub_key.indexOf("Last Name") && sub_key.indexOf("Email") && sub_key.indexOf("First Name")) > -1)
{
return "right format";
}
else
{
return "wrong format";
}
}
}
function process_wb(wb)
{
var output = "";
switch(get_radio_value("format"))
{
case "json":
output = JSON.stringify(to_json(wb), 2, 2);
break;
default:
output = JSON.stringify(to_json(wb), 2, 2);
}
if(out.innerText === undefined) out.textContent = output;
else out.innerText = output;
if(typeof console !== 'undefined') console.log("output", new Date());
}
var xlf = document.getElementById('xlf');
function handleFile(e)
{
rABS = document.getElementsByName("userabs")[0];
use_worker = document.getElementsByName("useworker")[0];
var files = e.target.files;
var f = files[0];
{
var reader = new FileReader();
var name = f.name;
reader.onload = function(e)
{
if(typeof console !== 'undefined') console.log("onload", new Date());
var data = e.target.result;
if(use_worker)
{
xw(data, process_wb);
}
else
{
var wb;
if(rABS)
{
wb = X.read(data, {type: 'binary'});
} else
{
var arr = fixdata(data);
wb = X.read(btoa(arr), {type: 'base64'});
}
process_wb(wb);
}
};
if(rABS) reader.readAsBinaryString(f);
else reader.readAsArrayBuffer(f);
}
}
if(xlf.addEventListener) xlf.addEventListener('change', handleFile, false);
</script>
</body>
</html>
That answer might work, but I don't think its exactly what you are requesting. In fact, based on your question and the documentation for SheetJS/js-xlsx I would suggest something like this:
function filePicked(oEvent) {
// Get The File From The Input
var oFile = oEvent.target.files[0];
var sFilename = oFile.name;
// Create A File Reader HTML5
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLSX.read(data, {type: 'binary'});
console.log(cfb)
cfb.SheetNames.forEach(function(sheetName) {
// Obtain The Current Row As CSV
var sCSV = XLS.utils.make_csv(cfb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_json(cfb.Sheets[sheetName]);
$("#my_file_output").html(sCSV);
console.log(oJS)
$scope.oJS = oJS
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);}
I tried it and it works fine. And whats more important, its a real answer to your question.
<script type="text/javascript">
document.querySelector("html").classList.add('js');
var fileInput = document.querySelector( ".input-file" ),
button = document.querySelector( ".input-file-trigger"),
the_return = document.querySelector(".file-return");
button.addEventListener( "keydown", function( event ) {
if ( event.keyCode == 13 || event.keyCode == 32 ) {
fileInput.focus();
}
});
button.addEventListener( "click", function( event ) {
fileInput.focus();
return false;
});
fileInput.addEventListener( "change", function( event ) {
var oFile = event.target.files[0];
var sFilename = oFile.name;
var reader = new FileReader();
// Ready The Event For When A File Gets Selected
reader.onload = function(e) {
var data = e.target.result;
var cfb = XLSX.read(data, {type: 'binary'});
// Loop Over Each Sheet
cfb.SheetNames.forEach(function(sheetName) {
var sCSV = XLS.utils.make_csv(cfb.Sheets[sheetName]);
var oJS = XLS.utils.sheet_to_json(cfb.Sheets[sheetName]);
alert(oJS);
alert(sCSV);
});
};
// Tell JS To Start Reading The File.. You could delay this if desired
reader.readAsBinaryString(oFile);
});

AJAX Upload Web App

I need some assistance please.
I am trying to create an ajax upload web app from scratch as a personal hobby.
I was able to get the files to upload to my uploads folder successfully, but I just can't seem to get the uploaded links to appear under the upload box and stay there permanently even after refreshing the web page.
I keep getting this error message in the google chrome browser console: Uncaught TypeError: Cannot read property 'length' of undefinedand it is pointing me to this line in the index.php:for(x = 0; x < data.succeeded.length; x = x + 1) {
Also the google chrome console is marking this as (anonymous function) in the upload.js file:o.options.finished(uploaded);
I had used some youtube videos as a guide, but I just can't seem to figure it out.
Kindly Help Me Please
This is the index.php code and below is the upload.php code also the upload.js code.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Uploader</title>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend>Upload files</legend>
<input type="file" id="file" name="file[]" required multiple>
<input type="submit" id="submit" name="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt"></span></span>
</div>
<div id="uploads" class="uploads">
Uploaded file links will appear here.
</div>
<script src="js/upload.js"></script>
<script>
document.getElementById('submit').addEventListener('click', function(e) {
e.preventDefault();
var f = document.getElementById('file'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload.php',
finished: function(data) {
var uploads = document.getElementById('uploads'),
succeeded = document.createElement('div'),
failed = document.createElement('div'),
anchor,
span,
x;
if(data.failed.length) {
failed.innerHTML = '<p>Unfortunately, the following failed:</p>';
}
uploads.innerText = '';
for(x = 0; x < data.succeeded.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = 'uploads/' + data.succeeded[x].file;
anchor.innerText = data.succeeded[x].name;
anchor.target = '_blank';
succeeded.appendChild(anchor);
}
for(x = 0; x < data.failed.length; x = x + 1 ) {
span = document.createElement('span');
span.innerText = data.failed[x].name;
failed.appendChild(span);
}
uploads.appendChild(succeeded);
upload.appendChild(failed);
},
error: function() {
console.log('Not working');
}
});
});
</script>
</form>
</body>
</html>
Upload.php code
<?php
header('Content-Type: application/json');
$uploaded = '';
$allowed = '';
$succedeed = '';
$failed = '';
if(!empty($_FILES['file'])) {
foreach($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key] === 0) {
$temp = $_FILES['file']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if(move_uploaded_file($temp, "uploads/{$file}") === true) {
$succedeed[] = array(
'name' => $name,
'file' => $file
);
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if(!empty($_POST['ajax'])) {
echo json_encode(array(
'succedeed' => $succedeed,
'failed' => $failed
));
}
}
This is the upload.js code
var app = app || {};
(function(o) {
"use strict";
//Private methods
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(event) {
var percent;
if(event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData(), i;
for(i = 0; i < source.length; i = i + 1) {
data.append('file[]', source[i]);
}
data.append('ajax', true);
return data;
};
setProgress = function(value) {
if(o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined) {
o.options.progressText.innerText = value ? value + '%' : '';
}
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
I think the problem is due to if(move_uploaded_file($temp, "uploads/{$file}") === true) try if(move_uploaded_file($temp, "uploads/{$file}") == true)
and also check data.succedeed spell in index.php

change background-image to image file in html 5

I'm using html5 for drag and drop image, my code is still running normally. But, i can only drop image to background-image in dropbox, not image file. So, i can't get and insert image into database. This is my code:
script
var holder = document.getElementById('leftbox'), state = document.getElementById('status');
if ( typeof window.FileReader === 'undefined') {
state.className = 'fail';
} else {
state.className = 'success';
state.innerHTML = 'Drop files here'
}
holder.ondragover = function() {
this.className = '';
return false;
};
holder.ondragend = function() {
this.className = '';
return false;
};
holder.ondrop = function(e) {
this.className = '';
e.preventDefault();
var file = e.dataTransfer.files[0], reader = new FileReader();
reader.onload = function(event) {
console.log(event.target);
holder.style.background = 'url(' + event.target.result + ') no-repeat center';
};
console.log(file);
reader.readAsDataURL(file);
return false;
};
HTML
<div class="medium-4 medium-centered columns">
<p id="status"></p>
<div id="leftbox"></div>
</div>
What should i do to change holder.style.background to image file? please help me :)
This should help you:
javascript onClick change background picture of div
$('#clickMe').on('click', function() { $('#changeMe').css('background-image', 'url(http://placehold.it/200x200/ff0000)'); })

Categories

Resources