I have been following a video tutorial on youtube for an AJAX upload, i know a fair amount of javascript, jquery, etc but this has me stumped.
my code is below, can anyone enlighten me as to why this is happening when i try to uploade more than one file or in some cases 1 file.
I have included my code below, its not perfect as i said i was follwoing along with a video tutorial.
<?php
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], "uploads/{$name}"))
{
$uploaded[] = $name;
}
}
if (!empty($_POST['ajax']))
{
die(json_encode($uploaded));
}
}
?>
<html>
<head>
<title></title>
<script type="text/javascript" src="upload.js"></script>
</head>
<style type="text/css">
#upload_progress {display: none;}
</style>
<body>
<div id="uploaded">
<?php
if(!empty($uploaded))
{
foreach ($uploaded as $name) {
echo '<div>'.$name.'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<form method="post" action="" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" multiple="multiple">
<input type="submit" id="submit" value="upload">
</form>
</body>
</html>
And my JS file is
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");
});
request.addEventListener('readystatechange', function(event) {
if (this.readyState == 4) {
if (this.status == 200)
{
var links = document.getElementById('uploaded');
console.log(this.response);
var uploaded = JSON.parse(this.response);
var div, a;
for (var i = 0; i < uploaded.length; i++)
{
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'uploads/' + uploaded[i]);
a.appendChild(document.createTextNode(uploaded[i]));
div.appendChild(a);
links.appendChild(div);
}
} else {
console.log("error" + this.response);
}
}
});
request.open('POST', 'index.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);
});
Initially the video had me using eval for the variable uploaded, i changed this to JSON.parse, i don't want a quick fix but rather an answer as to why this isn't working?
Thanks
Ben
I found out what the problem was, inside the php.ini file there is a size restriction on my server for file uploads, i increased that and it works fine now.
Anyone else who has the same problem check your upload size!
Related
I want to prevent user from predicting the target script (test.php) AND do the whole "counter" logic on the server side.
I don't know how to achieve it with PHP.
I would like to open the file from the server side with PHP so the client will not have the possibility to see and know what file will open after 15 clicks. Because by typing the URL of the file it is possible to open it even before 15 clicks.
Thanks
HTML
<div id='overlay' class='overlay'></div>
<div class="view" id="view"></div>
<div class="canvas">
<div id="totalCounter" class="total-counter"></div>
<button id="clap" class="clap-container" tabindex="-1"></button>
<div id="clicker" class="click-counter">
<span class="counter"></span>
</div>
</div>
JAVASCRIPT
let accCounter = 0;
let totalCount = 0;
document.getElementById('totalCounter').innerText = totalCount;
document.getElementById('clap').onclick = function() {
const clap = document.getElementById('clap');
const clickCounter = document.getElementById("clicker");
upClickCounter();
loadDoc();
}
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter ++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("view").innerHTML = this.responseText;
}
};
xhttp.open("GET", "clickcheck.php", true);
xhttp.send();
document.getElementById("view").style.visibility="visible";
if (totalCount + accCounter%15) {
document.getElementById('view').style.visibility="hidden";
}
document.getElementById('overlay').style.display = 'block';
if (totalCount + accCounter%15) {
document.getElementById('overlay').style.display = 'none';
}
}
clickcheck.php:
<?php
session_start();
if (!array_key_exists('clickcount', $_SESSION)) {
$_SESSION['clickcount'] = 1;
}
if ($_SESSION['clickcount'] < 15) {
header('HTTP/1.1 404 Not found');
exit();
} else {
include("test.php");
}
?>
I need some help. I am trying to make howler.js add songs from a directory via ajax, but it is not working.
I am doing a combination of this:
https://www.w3schools.com/xml/ajax_php.asp
https://www.dyclassroom.com/reference-javascript/work-with-audio-in-javascript-using-howler-js
The goal is to get howler to play the first mp3 that is in the folder scanned by php after the first sound has ended. The names in the folder will be random. The problem is that the howler src input does not work! What am I doing wrong?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<script src="howler/src/howler.core.js"></script>
<button id='howler-play'>Play</button>
<button id='howler-pause'>Pause</button>
<button id='howler-stop'>Stop</button>
<button id='howler-volup'>Vol+</button>
<button id='howler-voldown'>Vol-</button>
<button id='txt1' onclick="showHint()">Go</button>
<br><br>
<form action="">
First name: <input type="text" id="txt1x" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
<script>
var filename = '1';
function showHint() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
var x = this.responseText;
console.log(this.responseText);
//x = 'howler/audio/80s_vibe.mp3';
//console.log(x);
var howler_example = new Howl({
src: [x],
volume: 0.5,
autoplay: true,
});
howler_example.once('load', function(){
howler_example.play();
});
}
};
xhttp.open("GET", "gettrack.php", true);
xhttp.send();
}
</script>
<script type="text/javascript">
$(function(){
var howler_example = new Howl({
src: ['howler/audio/snap.mp3'],
volume: 0.5,
onend: function() {
console.log('Finished end 1!');
showHint();
console.log(filename);
}
});
$("#howler-play").on("click", function(){
if (howler_example.playing()) {
//console.log('position 1');
}
else {
howler_example.play();
}
});
$("#howler-pause").on("click", function(){
howler_example.pause();
});
$("#howler-stop").on("click", function(){
howler_example.stop();
});
$("#howler-volup").on("click", function(){
var vol = howler_example.volume();
vol += 0.1;
if (vol > 1) {
vol = 1;
}
howler_example.volume(vol);
});
$("#howler-voldown").on("click", function(){
var vol = howler_example.volume();
vol -= 0.1;
if (vol < 0) {
vol = 0;
}
howler_example.volume(vol);
});
});
</script>
</body>
</html>
and PHP file gettrack.php
$path = 'howler/audio/';
$files = array_diff(scandir($path), array('.', '..'));
$hint = $files[2];
echo "howler/audio/" . $hint;
I'm having a weird issue I created an app to open PNG and PDF's. The problem is when I try to open PDF files larger than 2,000 Kb it will not display, however PNG's have no problem. I'm confused as too why this is.
<html lang="en"><head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" media="all" href="styles.css">
</head>
<body>
<ul>
</ul>
<fieldset>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000">
<div>
<label for="fileselect">Files to upload:</label>
<input type="file" id="fileselect" name="file-select[]" multiple="multiple">
<div id="filedrag" style="display: block;">or drop files here</div>
</div>
<div id="submitbutton" style="display: none;">
<button type="submit">Upload Files</button>
</div>
<div id="sortbutton">
<button type="submit">Submit</button>
</div>
<div id="resetbutton">
<button type="submit">Reset</button>
</div>
</fieldset>
</form>
<div id="messages">
</div>
<script src="filedrag.js"></script>
</body></html>
var files;
(function() {
// getElementById
function $id(id) {
return document.getElementById(id);
}
// output information
function Output(msg) {
var m = $id("messages");
m.innerHTML = msg + m.innerHTML;
}
// file drag hover
function FileDragHover(e) {
e.stopPropagation();
e.preventDefault();
e.target.className = (e.type == "dragover" ? "hover" : "");
}
// file selection
function FileSelectHandler(e) {
// cancel event and hover styling
FileDragHover(e);
// fetch FileList object
var files = e.target.files || e.dataTransfer.files;
// process all File objects
for (var i = 0, f; f = files[i]; i++) {
ParseFile(f);
}
}
// output file information
function ParseFile(file) {
// display an image
if (file.type.indexOf("application") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<object data="' + e.target.result + '"></object></p>');
}
reader.readAsDataURL(file);
}
if (file.type.indexOf("image") == 0) {
var reader = new FileReader();
reader.onload = function(e) {
files.push("<p align=left><strong>" + file.name + ":</strong><br />" +
'<img src="' + e.target.result + '" height="500px" width="500px"></p>');
}
reader.readAsDataURL(file);
}
}
function sortFiles() {
files.sort().reverse();
for (var i = 0; i < files.length; ++i) {
Output(files[i]);
}
}
function resetWindow(){
window.location.reload(true)
}
// initialize
function Init() {
var fileselect = $id("fileselect"),
filedrag = $id("filedrag"),
submitbutton = $id("submitbutton"),
sortbutton = $id("sortbutton"),
resetbutton = $id("resetbutton");
files = new Array();
// file select
fileselect.addEventListener("change", FileSelectHandler, false);
// is XHR2 available?
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// file drop
filedrag.addEventListener("dragover", FileDragHover, false);
filedrag.addEventListener("dragleave", FileDragHover, false);
filedrag.addEventListener("drop", FileSelectHandler, false);
filedrag.style.display = "block";
// remove submit button
submitbutton.addEventListener("click", sortFiles , false); //style.display = "none";
sortbutton.addEventListener("click", sortFiles , false);
resetbutton.addEventListener("click", resetWindow , false);
}
}
// call initialization file
if (window.File && window.FileList && window.FileReader) {
Init();
}
})();
As I said you try to post a PDF file larger than 2000 Kb it will not display, PNG however will display
I fixed it I hardcoded the path to display the Files
I had the same issue like yours and I resolved in this way:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="height: 100%;">
<button onclick="getFile(event)">Get File</button>
<input id="pdfInputFile" type="file" accept="application/pdf" style="display:none" onchange="loadPDF(this);" />
<object id="pdfViewer" type="application/pdf" style="height:100%; width:100%;border:solid 1px" >
</object>
</body>
<script>
function getFile(e) {
e.preventDefault();
document.getElementById("pdfInputFile").click();
}
function loadPDF(input) {
if (input.files && input.files[0]) {
showFile(input.files[0])
}
}
function showFile(blob){
// It is necessary to create a new blob object with mime-type explicitly set
// otherwise only Chrome works like it should
var newBlob = new Blob([blob], {type: "application/pdf"});
// Create a link pointing to the ObjectURL containing the blob.
const data = window.URL.createObjectURL(newBlob);
document.getElementById("pdfViewer").setAttribute('data', data);
setTimeout(function(){
// For Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(data);
}, 100);
}
</script>
</html>
I'm trying to use JavaScript to display data from an XML file. My data isn't being displayed to the web page and I'm not sure why.
Any help/advice would be appreciated. My code is displayed below.
NOTE - I have no experience with XML so be aware that I am completely new to it.
<script>
var xmlData;
function loadXml () {
var filename = "CDLibrary.xml";
var XMLhttp = new XMLHttpRequest();
XMLhttp.open("GET", filename, true);
var ok = true;
try {
XMLhttp.send();
}
catch(err) {
ok = false;
alert ("Database not found");
}
if (ok) {
xmlData = XMLhttp.responseXML;
displayXml(xmlData);
}
}
function displayXml () {
var CdElements;
var CdTitle;
var count;
CdElements = xmlData.getElementsByTagName("CD");
for (count = 0; count < CdElements.length; count=count+1) {
CdTitle = CdElements[count].getElementsByTagName("title");
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + CdTitle[0].childNodes[0].nodeValue + "</br>";
}
}
</script>
</head>
<body>
<div>
<p id="output">
</p>
<p id="buttons">
<input type="button" id="btnDisplay" value="Display CDs" onclick="loadXml();">
</div>
</body>
<html>
<head><title>Import XML Data</title></head>
<body>
<div>
<p id="output">
</p>
<p id="buttons">
<input type="button" id="btnDisplay" value="Display CDs" onclick="loadXml()">
</div>
<script>
var xmlData;
function loadXml () {
var filename = "CDLibary.xml";
var XMLhttp = new XMLHttpRequest();
XMLhttp.open("GET", filename, true);
var ok = true;
try {
XMLhttp.send();
}
catch(err) {
ok = false;
alert ("Database not found");
}
if (ok) {
xmlData = XMLhttp.responseXML;
displayXml(xmlData);
}
}
function displayXml(xmlDataBase) {
var CdElements;
var CdTitle;
var count;
CdElements = xmlDataBase.getElementsByTagName("CD");
for (count = 0; count < CdElements.length; count=count+1) {
CdTitle = CdElements[count].getElementsByTagName("title");
document.getElementById("output").innerHTML = document.getElementById("output").innerHTML + CdTitle[0].childNodes[0].nodeValue + "</br>";
}
}
</script>
</body>
</html>
You're not using the var xmlData instead you're using a var xmlDataBase. Replace you code to:
CdElements = xmlData.getElementsByTagName("CD");
And since you're using a global var xmlData, it's available inside displayXml function, in this case no need for function displayXml(xmlDataBase) if you use function displayXml() it'll be enough.
Using the w3schools link and changing some information and changing the directory I got it working. There must be an error in the template i was following, thank you all for your time and efforts.
<html>
<style>
table,th,td {
border : 1px solid black;
border-collapse: collapse;
}
th,td {
padding: 5px;
}
</style>
<body>
<button type="button" onclick="loadDoc()">Get my CD collection</button>
<br><br>
<table id="demo"></table>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "CDLibrary.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<tr><th>Artist</th><th>Title</th></tr>";
var x = xmlDoc.getElementsByTagName("CD");
for (i = 0; i <x.length; i++) {
table += "<tr><td>" +
x[i].getElementsByTagName("performer")[0].childNodes[0].nodeValue +
"</td><td>" +
x[i].getElementsByTagName("title")[0].childNodes[0].nodeValue +
"</td></tr>";
}
document.getElementById("demo").innerHTML = table;
}
</script>
</body>
</html>
I was following a tutorial about how to make an javascript/ajax upload system with progress (%) indicator . I have successfully added a css progress bar indicator to it .
But i have a problem that i can't solve is how to put to condition of upload like: type, file size, file is set, ....
here is my code (upload.php)
<?php
foreach($_FILES['file']['name'] as $key => $name){
if ($_FILES['file']['error'][$key] == 0 && move_uploaded_file($_FILES['file']['tmp_name'][$key], "files/{$name}")){
$uploaded[] = $name;
}
}
if(!empty($_POST['ajax'])){
die(json_encode($uploaded));
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="upload.js"></script>
</head>
<body>
<div id="uploaded">
<?php
if (!empty($uploaded)){
foreach ($uploaded as $name){
echo '<div>',$name,'</div>';
}
}
?>
</div>
<div id="upload_progress"></div>
<div>
<form action="" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file[]" />
<input type="submit" id="submit" value="upload" />
</form>
and this is the javascript file (upload.js):
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) +' %'));
document.getElementById("loading-progress-17").style.width= 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.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;
for (var i = 0; i < uploaded.length; ++i){
div = document.createElement('div');
a = document.createElement('a');
a.setAttribute('href', 'files/' + 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);
});
I just need and example of how to check file size is less than 50MB and i can do the other checks my self i just don't know how to check condition in this upload system.
Thanks in advance
If you want to check something like the size, you can realize it with your code easily:
Take a look at these lines in your code:
for (var i = 0; i < fileInput.files.length; ++i){
data.append('file[]', fileInput.files[i]);
}
This is where the files are added to the FormData which is then submitted to the server. You can add the conditions here, e.g. a size check:
for (var i = 0; i < fileInput.files.length; ++i){
//file.size is given in bytes
if(fileInput.files[i].size <= MAX_FILESIZE_IN_BYTES){
data.append('file[]', fileInput.files[i]);
}
}
I hope this helps.