File Upload Progress for Dynamic Dropdown File Upload - php

I have made a dynamic dropdown file upload system where user can choose the engineering stream, then the semester and then subject, and the file gets uploaded in the desired directory. This works fine normally. I came across the Javascript/AJAX File Upload Progress tutorial from PHPAcademy, things worked fine until I got stuck into this.
Without adding the javascript file (for upload progress), the files get uploaded in the correct directory, show no errors in the firebug, and also gives the link to the file after it gets uploaded.
But after I add the JS file, the link doesn't come after upload, it gets uploaded in the root directory always, it shows the progress though, and the console shows two errors.
Here is my PHP code:
<?php
if(isset($_POST['upload'])) {
$path1=$_POST['one']."/";
$path2=$_POST['two']."/";
$path3=$_POST['three']."/";
$upload_path=$path1.$path2.$path3;
}
else {
echo "Follow the instructions before uploading a file";
}
if(!empty($_FILES['file'])) {
foreach($_FILES['file']['name'] as $key => $name) {
if($_FILES['file']['error'][$key]==0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], $upload_path."$name")) {
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])) {
die(json_decode($uploaded));
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> SRMUARD - Upload </title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
function val()
{
if(document.uploads.three.selectedIndex == 0)
{
alert("Please choose all the appropriate options");
}
}
</script>
<script>
$(function() {
$("#text-one").change(function() {
$("#text-two").load("textdata/" + $(this).val() + ".txt");
});
$("#text-two").change(function() {
$("#text-three").load("textdata/" + $(this).val() + ".txt");
});
});
</script>
</head>
<body>
<div value="<?php $upload_path ?>" id="uploadpath"></div>
<div id="uploaded">
<?php
if(!empty($uploaded)) {
foreach($uploaded as $name) {
echo 'File Link: '.'<a href="' . $upload_path . $name . '" >', $name, '</a><br/>';
}
}
?>
</div>
<div id="upload_progress" style="display: none"></div>
<div>
<form action="" method="POST" enctype="multipart/form-data" name="upload" id="upload">
<label for="file">Choose a file: </label><br/>
<input type="file" name="file[]" id="file" multiple="multiple"><br/><br/>
<select id="text-one" name="one">
<option selected value="base">Select Department</option>
<option value="CSE" name="cse">Computer Science Engineering</option>
<option value="ECE" name="ece">Electronics & Communication Engineering</option>
<option value="MECH" name="mech">Mechanical Engineering</option>
</select><br/><br/>
<select id="text-two" name="two"> //Displays options dynamically using text files
<option>Select Semester</option>
</select><br/><br/>
<select id="text-three" name="three"> //Displays options dynamically using text files
<option>Select Subject</option>
</select><br/><br>
<input type="submit" name="upload" id="submit" value="Upload" onClick="val()" />
</form>
<div>
</body>
</html>
And here is my javascript code:
var handleUpload = function(event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('ajax', true);
for(var i = 0; i < fileInput.files.length; ++i) {
data.append('file[]', fileInput.files[i]);
}
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event) {
if(event.lengthComputable) {
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) + '%'));
}
});
request.upload.addEventListener('load', function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed due to some reason!');
});
request.addEventListener('readystatechange', function(event) {
if(this.readyState == 4) {
if(this.status == 200) {
var links = document.getElementById('uploaded');
var uploaded = eval(this.response);
var div, a;
var phpval = document.getElementById('uploadpath').value;
for(var i=0; i < uploaded.length; ++i) {
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', phpval + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
} else {
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST','upload.php');
request.setRequestHeader('Cache-Control','no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
}
window.addEventListener('load',function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
And the errors shown in the console are:
TypeError: document.uploads is undefined
[Break On This Error]
if(document.uploads.three.selectedIndex == 0)
and
SyntaxError: missing ; before statement upload.js file line 47 which is var uploaded = eval(this.response);
And another place where I feel I am making a mistake is:
a.setAttribute('href', phpval + uploaded[i]);
The phpval must correspond to the dynamic upload link. I couldn't use the $upload_path in the JS, so made a div out of it, and then used to get the value like this:
var phpval = document.getElementById('uploadpath').value;
For the demo, you can refer this link, things will be more precise, please turn on your firebug console and check the errors and help me. I am not able to solve this.
Dynamic Dropdown File Upload with Progress Indication
Thank You

Also consider positioning of your script properly. Sometimes what happens is the place where you place your script might cause conflicts. I can see that you have the scripts for Dynamic Dropdown Functionality already. Try placing it after your form and check if it works.
Hope this helps.

There are many JQuery options you could try. Here is one from Blueimp. Hope this helps.

Related

Basic jquery & PHP session.upload_progress.name

I am trying to get the file progress working with the new session.upload_progress.name functionality in PHP 5.4.
So far my code is this:
<?
session_start();
?>
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function () {
$("#jimbo").submit(function () {
setInterval(function() {
$.ajax({
url: "ajx.php",
success: function (data) {
$("#feedback").html(data + Math.random(999));
}
});
//$("#feedback").html("hello " + Math.random(999));
},500);
//return false;
});
});
</script>
</head>
<body>
<h1>Upload</h1>
<br/>
<form action="test.php" method="POST" enctype="multipart/form-data" id='jimbo'>
<input type="hidden" name="<?=ini_get('session.upload_progress.name'); ?>" value="myupload" />
<input type="file" name="file1" />
<input type="submit" id='submitme' />
</form>
<div id="feedback">Hello</div>
</body>
</html>
And then the ajx.php file:
<? session_start(); ?>
<pre>
<?
echo "SESSIONVAR<br/>";
var_dump($_SESSION);
?>
</pre>
Now. When I click the submit button (after selecting a file), The file starts uploading, but the setinterval doesnt start. However, If I have the return false; in there, I get the setInterval results, but the file doesnt start uploading. If I submit the file without returning false, and in a seperate window view the contents of ajx.php, I can see that the variable is working fine and updating. So how do I get the #feedback div to update once the form has been clicked?
note the session array is populated, the problem here is with the jquery and nothing else.
You can achieve similar functionality using javascript XMLHttpRequest objects 'upload' property. It has a couple of events you can hook into, 'progress' is one of them.
here's a sample I've used. It will add a row with the progression (in %) to a <div class="progression"> for each file from a <input type="file"> field:
function startUpload() {
var fileInput = document.getElementById("file1");
$('.progression').show();
for(var i = 0;i<fileInput.files.length;i++) {
doFileUpload(fileInput.files[i]);
}
}
function doFileUpload(file) {
var xhr = new XMLHttpRequest();
var data = new FormData();
var $progress = $('<div class=\"progress\"><p>' + file.name + ':</p><span>0</span>%</div>');
$('div.progression').append($progress);
data.append("file", file);
data.append("album", $("#album").val());
xhr.upload.onprogress = function(e) {
var percentComplete = (e.loaded / e.total) * 100;
$progress.find('span').text(Math.ceil(percentComplete));
};
xhr.onload = function() {
if (xhr.status == 200) {
var result = JSON.parse(xhr.responseText);
if(result.success == "true") {
console.log("Great success!");
}
else {
console.log("Error! Upload failed");
}
};
xhr.onerror = function() {
console.log("Error! Upload failed.");
};
xhr.open("POST", "/_admin/_inc/upload.php", true);
xhr.send(data);
}

Getting details selected images in php

I'm using html5 js to upload multiple images. Why when we upload multiple images does the result (PHP: print_r($_FILES['upimg']['name'])) only shows details of the last selected image?
For Example:(i selected following image name)
111111.gif
222222.gif
333333.gif
PHP code only last selected image show: 333333.gif
But I want to show details from all the images.
What do I do?
DEMO: http://codepad.viper-7.com/16abeG
FULL CODE:
<!doctype html>
<html>
<head>
<?php
if($_FILES){
echo '<pre>';
print_r($_FILES['upimg']['name']);
//for($i=0; $i<count($_FILES['name']); $i++){
//if ($_FILES['error'][$i] == 0) {
////do your stuff here, each image is at $_FILES['tmp_name'][$i]
//}
//}
}
?>
<title>file input click() demo</title>
<script type="text/javascript">
function doClick() {
var el = document.getElementById("fileElem");
if (el) {
el.click();
}
}
function handleFiles(files) {
var d = document.getElementById("fileList");
if (!files.length) {
d.innerHTML = "<p>No files selected!</p>";
} else {
var list = document.createElement("ul");
d.appendChild(list);
for (var i=0; i < files.length; i++) {
var li = document.createElement("li");
list.appendChild(li);
var img = document.createElement("img");
img.src = window.URL.createObjectURL(files[i]);;
img.height = 60;
img.onload = function() {
window.URL.revokeObjectURL(this.src);
}
li.appendChild(img);
var info = document.createElement("span");
info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
li.appendChild(info);
}
}
}
</script>
</head>
<body>
<p>This is a demo of calling <code>click()</code> on a form's file picker.
Note that the file input element is actually hidden here, so the
user doesn't have to see the path to the selected file.</p>
Select some files
<div id="fileList">
<p>No files selected!</p>
</div>
<form action="#" method="post" enctype="multipart/form-data">
<input name="upimg[]" type="file" id="fileElem" multiple accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<input type="submit" value="Click to see the result">
</form>
</body>
</html>
Your logic i think is wrong you use HTML 5, but not upload images via AJAX you use form for this method.
Miltiple is only HTML 5 and you can't use for PHP purpose without AJAX.
I created similar plugin you can check : https://github.com/dimitardanailov/js-control-files-uploader
Try wrapping it in a for loop somewhat like the code you have commented out....
if(isset($_FILES["upimg"]["name"])) {
for($i=0; $i<count($_FILES["upimg"]["name"]);$i++) {
echo $_FILES["upimg"]["name"][$i];
}
}
why don't you use tag before any of the .parent div?
for width ratio you of course can do it using jquery.
myElement.width = (parentElement.width/100)*40

PHP/JS script is not working inside HTML

I am adding an upload function to the HTML div, but for some reason it is not working. I have also created a php file with the same scripts I have added to the div and did the action="upload-page.php", but it does not get the php page either. What could be the problem?
Here is the code:
<div class="wall-ptype-cnt wall_text" >
__post_wall_text__
<form method="post" action="upload-page.php" enctype="multipart/form-data">
<input name="filesToUpload[]" id="filesToUpload" type="file" multiple="" />
<script language="javascript" type="text/javascript">
var input = document.getElementById('filesToUpload');
var list = document.getElementById('fileList');
while (list.hasChildNodes()) {
list.removeChild(ul.firstChild);
}
for (var x = 0; x < input.files.length; x++) {
var li = document.createElement('li');
li.innerHTML = 'File ' + (x + 1) + ': ' + input.files[x].name;
list.append(li);
}
</script>
<?php if(count($_FILES['uploads']['filesToUpload'])) {
foreach ($_FILES['uploads']['filesToUpload'] as $file) {
//do your upload stuff here
echo $file;
}
}
?>
</form>
</div>
Why does the php page is not being processed and why the script is not working as well?
The script I have in upload-page.php is the same I am putting inside html.
A couple of mistakes in your code:
"list.removeChild(ul.firstChild);" should be "list.removeChild(list.firstChild);"
"list.append(li);" should be "list.appendChild(li);"

PHP AJAX Image Upload Example Not Uploading

My code produces no errors on the console. When I click the upload button, nothing happens. There is a post sent to itself, as instructed in the tutorial I used but the image is not uploaded to my folder and it is not displayed on my page. Barring the fact I know I should use jquery (I will make the transition once I get it to upload to the folder) what is wrong with my code?
<?php
if (!empty($_FILES)) {
$name = $_FILES['file']['name'];
if ($_FILES['file']['error'] == 0) {move_uploaded_file($_FILES['file']
['tmp_name'], "post_images/" . $name))}
}
?>
<script type="text/javascript">
var handleUpload = function (event) {
event.preventDefault();
event.stopPropagation();
var fileInput = document.getElementById('file');
var data = new FormData();
data.append('file', fileInput.files[1]);
var request = new XMLHttpRequest();
request.upload.addEventListener('progress', function(event){
if (event.lengthComputable)
{
var percent = event.loaded / event.total;
var progress = document.getElementById('upload_progress');
while(progress.hasChildNodes()) {
progress.removeChild(progress.firstChild);
}
progress.appendChild(document.createTextNode(Math.round(percent * 100) +
'%'));
}
});
request.upload.addEventListener('load',function(event) {
document.getElementById('upload_progress').style.display = 'none';
});
request.upload.addEventListener('error', function(event) {
alert('Upload failed');
});
request.open('POST', 'upload.php');
request.setRequestHeader('Cache-Control', 'no-cache');
document.getElementById('upload_progress').style.display = 'block';
request.send(data);
};
window.addEventListener('load', function(event) {
var submit = document.getElementById('submit');
submit.addEventListener('click', handleUpload);
});
</script>
<div id="uploaded">
<?php
if (!empty($name)) {
echo '<img src="post_images/' . $name . '" width="100" height="100" />';
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<div>
<input type="file" id="file" name="file" />
<input type="submit" id="submit" value="upload" />
</div>
</form>
</div>
There is only one file in a non- multiple file input element, fileInput.files[1] attempts to use the second file.
data.append('file', fileInput.files[0]);

php code to call javascript function returns function is not defined

The code bellow tries to ask the user to upload kml file and then saves the file at the same time it shows the kml data in google maps using google maps api v2. I could successfully take the kml file and saves it at a specific directory, HOWEVER, i am facing some problem in displaying the file on google maps immediately after the user clicks on KML TEST button. The error is Uncaught ReferenceError: showKML is not defined
Here is the code that I used
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Find latitude and longitude with Google Maps</title>
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAgrj58PbXr2YriiRDqbnL1RSqrCjdkglBijPNIIYrqkVvD1R4QxRl47Yh2D_0C1l5KXQJGrbkSDvXFA"
type="text/javascript"></script>
<?php
$upload = $_SERVER['PHP_SELF'];
if(isset($_POST['kmltest'])) {
$target_path = "uploads/";
$fn = basename( $_FILES['uploadedfile']['name']);
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
//echo $target_path ;
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) {
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded";
echo "<script type=\"text/javascript\"> showKML(); </script>";
}
else{
echo "There was an error uploading the file, please try again!";
}
}
?>
<script src="egeoxml.js" type="text/javascript"></script>
<script type="text/javascript">
var map;
var options = {};
var shapeCounter_ = 0;
function initialize() {
if (GBrowserIsCompatible()) {
map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(25.22903, 55.46612), 13);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.clearOverlays();
document.getElementById("lat").value = "25.22903";
document.getElementById("lng").value = "55.46612";
}
}
function startShape() {
initialize();
document.getElementById('lat').disabled = true;
document.getElementById('lng').disabled = true;
var polygon = new GPolygon([],"ff0000", 2, 0.7,"ff0000",0.2);
startDrawing(polygon, "Shape " + (++shapeCounter_), function() {
var cell = this;
var area = polygon.getArea();
cell.innerHTML = (Math.round(area / 10000) / 100) + "km<sup>2</sup>";
});
showcoor(polygon);
}
function startDrawing(poly, name, onUpdate) {
map.addOverlay(poly);
poly.enableDrawing(options);
poly.enableEditing({onEvent: "mouseover"});
poly.disableEditing({onEvent: "mouseout"});
GEvent.addListener(poly, "endline", function() {
GEvent.addListener(poly, "click", function(latlng, index) {
if (typeof index == "number") {
poly.deleteVertex(index);
}
});
});
}
function showcoor (poly) {
GEvent.addListener(poly, "endline", function() {
GEvent.addListener(poly, "click", function() {
var str= "" ;
for (var i = 0, I = this.getVertexCount(); i < I; ++i) {
var xy = this.getVertex(i);
str += xy.lat() + ', ' + xy.lng() + '<br />';
}
alert (str);
});
});
}
function drawpoint() {
//initialize();
document.getElementById('lat').disabled = false;
document.getElementById('lng').disabled = false;
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
var center = new GLatLng(parseFloat(lat), parseFloat (lng));
map.setCenter(center, 7);
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "dragend", function() {
var point = marker.getPoint();
map.panTo(point);
document.getElementById("lat").value = center.lat().toFixed(5);
document.getElementById("lng").value = center.lat().toFixed(5);
});
GEvent.addListener(map, "moveend", function() {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {draggable: true});
map.addOverlay(marker);
document.getElementById("lat").value = center.lat().toFixed(5);
document.getElementById("lng").value = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function() {
var point =marker.getPoint();
map.panTo(point);
document.getElementById("lat").value = point.lat().toFixed(5);
document.getElementById("lng").value = point.lng().toFixed(5);
});
});
}
function showKML() {
//alert(filename);
initialize();
document.getElementById('lat').disabled = true;
document.getElementById('lng').disabled = true;
var exml;
exml = new EGeoXml("exml", map, ("uploads/test.kml"));
exml.parse();
exml.show();
}
</script>
</head>
<body onload="initialize()" onunload="GUnload()" >
<form action = <?php echo $upload; ?> method = "post" enctype="multipart/form-data"/>
<p align="left">
<table>
<tr>
<td><b>Latitude</b></td>
<td><b>Longitude</b></td>
</tr>
<tr>
<td>
<input type="text" name="lat" id="lat" /></td>
<td>
<input type="text" name="lng" id="lng" /></td>
<td>
<input type="button" name="point" id="point" value="Point" onclick="drawpoint()" /><td>
<input type="button" name="shape_b" id="shape_b" value="Poly" onclick="startShape()" /><td>
<input type="submit" name="kmltest" id="kmltest" value="KML TEST" /> </td></tr>
<tr>
<td>
<input type="file" name="uploadedfile" id="uploadedfile" />
</td>
</tr>
</table>
</p>
<p>
<div align="center" id="map" style="width: 600px; height: 400px"><br/></div>
</p>
<script type="text/javascript">
//<![CDATA[
if (typeof _gstat != "undefined") _gstat.audience('','pagesperso-orange.fr');
//]]>
</script>
</form>
</body>
</html>
your assistance is highly appreciated
JavaScript <script> blocks are evaluated in blocks.
Within the same block, a function can be called before it's defined, because function declarations are evaluated before the rest of the code.
However, when you move function showKML(){} to a different block, the function is called before it's defined, hence the error.
To solve the problem, you have to move the function declaration before the <?php .. ?> block, where showKML is called.
A JSFiddle to demonstrate the problem: http://jsfiddle.net/SGbfu/1/
More detailled explanation:
When <script> and </script> is encountered, the code between is directly evaluated.
All functions, declared using function x(){} are evaluated first. Then, the rest of the code is considered.
Step 1-2 is repeated, till all <script> blocks in the document are evaluated.
Example:
<script>
f(); // No error, f is declared below
function f(){ alert('f() called'); }
g(); // Error: g is not defined before, or within this block
</script>
<script>
function g(){}
</script>
you need to move the <script> block with the function definitions to the top. At the time you call the function showKML() its not yet defined. You should bind showKML() to the document ready event. (e.g. put the function call inside your initialize() function that is already called on the page load event)
Also i suggest you move the javascript code definition to an external file and include it just like you include the google maps API - this avoids loading the code with each page refresh and reduces traffic and page load.

Categories