Uncaught Syntax Error: Unexpected end of input Javascript - javascript

I want to learn JavaScript and I tried to created a multiple Ajax uploader. I encountered this error:
In Google Chrome :
Uncaught SyntaxError: Unexpected end of input,
In Mozilla Firebug
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
uploaded = JSON.parse(this.response);
And my JavaScript file
var app = app || {};
(function(o) {
"use strict";
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);//this is where error occurs
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));
my Php file
<?php
header('Content-Type:application/json');
$uploaded = [];
$allowed = ['MP4','PNG','JPG'];
$succeded = [];
$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 (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeded[] = array(
'name' => $name,
'file' => $file
);
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeded' => $succeded,
'failed' => $failed
));
}
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset ="UTF-8"/>
<title>Ajax Uploader</title>
<link rel="stylesheet" href="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>
</form>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
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('upload'),
succeeded = document.createElement('div'),
failed = document.createElement('div'),
anchor,
span,
x;
if (data.failed.length) {
failed.innerHTML = '<p>Unfortunately, the following is an error:</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);
uploads.appendChild(failed);
},
error: function() {
console.log('not working');
}
});
});
</script>
Any Ideas?

Related

drag & drop (and choose file) uploading

How can I combine these two projects like this(no-dropzone.js):
I want only image file uploading (pnp, jpg etc.)
Project 1:
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>File upload</title>
</head>
<body>
<form action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="upload">
</form>
</body>
</html>
upload.php
<?php
if(isset($_FILES['file'])) {
$file = $_FILES['file'];
// File properties
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
// Work out the file extension
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('txt', 'jpg');
if(in_array($file_ext, $allowed)) {
if($file_error === 0) {
if($file_size <= 2097152) {
$file_name_new = uniqid('', true) . '.' . $file_ext;
$file_destination = 'uploads/' . $file_name_new;
if(move_uploaded_file($file_tmp, $file_destination)) {
echo $file_destination;
}
}
}
}
}
?>
with
Project 2
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Drag & Drop Uploading</title>
<link rel="stylesheet" href="css/global.css">
</head>
<body>
<div id="uploads"></div>
<div class="dropzone" id="dropzone">Drop files here to upload</div>
<script>
(function() {
var dropzone = document.getElementById('dropzone');
var displayUploads = function(data) {
var uploads = document.getElementById('uploads'),
anchor,
x;
for(x = 0; x < data.length; x = x + 1) {
anchor = document.createElement('a');
anchor.href = data[x].file;
anchor.innerText = data[x].name;
uploads.appendChild(anchor);
}
};
var upload = function(files) {
var formData = new FormData(),
xhr = new XMLHttpRequest(),
x;
for(x = 0; x < files.length; x = x + 1) {
formData.append('file[]', files[x]);
}
xhr.onload = function() {
var data = JSON.parse(this.responseText);
displayUploads(data);
}
xhr.open('post', 'upload.php');
xhr.send(formData);
};
dropzone.ondrop = function(e) {
e.preventDefault();
this.className = 'dropzone';
upload(e.dataTransfer.files);
};
dropzone.ondragover = function() {
this.className = 'dropzone dragover'
return false;
};
dropzone.ondragleave = function() {
this.className = 'dropzone';
return false;
};
}());
</script>
</body>
</html>
upload.php
<?php
header('Content-Type: application/json');
$uploaded = array();
if(!empty($_FILES['file']['name'][0])) {
foreach($_FILES['file']['name'] as $position => $name) {
if(move_uploaded_file($_FILES['file']['tmp_name'][$position], 'uploads/' . $name)) {
$uploaded[] = array(
'name' => $name,
'file' => 'uploads/' . $name
);
}
}
}
echo json_encode($uploaded);
?>

Jquery file uploading JSON empty error

I'm following these videos (https://www.youtube.com/watch?v=Be-GSVO7PGQ&index=9&list=PLfdtiltiRHWHCzhdE0N1zmeFHlEuqxQvm) to create a jquery upload page to my website.
I get the following error on Chrome:
Uncaught SyntaxError: Unexpected end of input
And I get the following error on Firefox Firebug:
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Currently, my code looks like this:
upload.php:
<form action="upload_process.php" method="post" enctype="multipart/form-data" id="upload" class="upload">
<fieldset>
<legend><h3>Upload files</h3></legend>
<input type="file" id="file_upload" name="file_upload[]" required multiple>
<input type="submit" id="submit_upload" name="submit_upload" value="Upload">
<div class="bar">
<span class="bar-fill" id="pb"><span class="bar-fill-text" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
Uploaded files will appear here.
</div>
</fieldset>
</form>
<script src="js/upload.js"></script>
<script>
document.getElementById('submit_upload').addEventListener('click', function(e) {
e.preventDefault();
var f = document.getElementById('file_upload'),
pb = document.getElementById('pb'),
pt = document.getElementById('pt');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: 'upload_process.php',
finished: function(data) {
console.log(data);
},
error: function() {
console.log('not working');
}
});
});
</script>
upload.js
var app = app || {};
(function(o) {
"use strict";
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);
console.log(uploaded);
}
if (typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if (typeof o.options.error === 'function') {
o.options.error(uploaded);
}
}
});
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);
};
setProgress = function(value) {
};
o.uploader = function(options) {
o.options = options;
if (o.options.files !== undefined) {
ajax(getFormData(o.options.files.files));
}
};
}(app));
and my upload_process.php
<?php
//require_once('core/init.php');
header('Content-Type: application/json');
$uploaded = [];
$allowed = ['mp4', 'png', 'bmp', 'mp3', 'txt'];
$succeeded = [];
$failed = [];
if (!empty($_FILES['file_upload'])) {
foreach($_FILES['file_upload']['name'] as $key => $name) {
if ($_FILES['file_upload']['error'][$key] === 0) {
$temp = $_FILES['file_upload']['tmp_name'][$key];
$ext = explode('.', $name);
$ext = strtolower(end($ext));
$file = md5_file($temp) . time() . '.' . $ext;
if (in_array($ext, $allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded[] = array(
'name' => $name,
'file' => $file
);
$db = new DB();
$user = new User();
$units = new Units();
$size = filesize("uploads/" . $file);
$formattedSize = $units->formatSizeUnits($size);
$db->insert('files', array(
'user_id' => $user->data()->id,
'name' => $name,
'size' => $formattedSize,
'address' => 'uploads/' . $file . '',
'created' => date('Y-m-d H:i:s'),
'type' => $ext
));
/*Redirect::to('index');
Session::flash('');*/
} else {
$failed[] = array(
'name' => $name
);
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' => $failed
));
}
}
I know that the problem is propably that this:
uploaded = JSON.parse(this.response);
this.response returns nothing.
I just can't figure out why it returns nothing.

Trigger url after success of order placed in magento

I am using magento 1.8.1 and I am working on sms integration. I am trying to trigger a api url after clicking on placed order button. But as I new on magento I don't know where I put that url. After finding, I get these code of button
<div class="clear"></div>
<button style="float:left" onclick="oscPlaceOrder(this);"
id="onestepcheckout-button-place-order" type="button"
title="<?php echo $this->__('Place Order') ?>"
class="btn-proceed-checkout onestepcheckout-btn-checkout onestepcheckout-place">
<span>
<span><?php echo $this->__('Place order now') ?></span>
</span>
</button>
</div>
now here is one function oscPlaceOrder:
function oscPlaceOrder(element) {
var validator = new Validation('one-step-checkout-form');
var form = $('one-step-checkout-form');
if (validator.validate()) {
if (($('p_method_hosted_pro') && $('p_method_hosted_pro').checked) || ($('p_method_payflow_advanced') && $('p_method_payflow_advanced').checked)) {
$('onestepcheckout-place-order-loading').show();
$('onestepcheckout-button-place-order').removeClassName('onestepcheckout-btn-checkout');
$('onestepcheckout-button-place-order').addClassName('place-order-loader');
$('ajaxcart-load-ajax').show();
checkAjax('<?php echo $this->getUrl('onestepcheckout/index/saveOrderPro', array('_secure' => true)); ?>');
} else {
if (checkpayment()) {
element.disabled = true;
var already_placing_order = true;
disable_payment();
$('onestepcheckout-place-order-loading').show();
$('onestepcheckout-button-place-order').removeClassName('onestepcheckout-btn-checkout');
$('onestepcheckout-button-place-order').addClassName('place-order-loader');
//$('one-step-checkout-form').submit();
var options = document.getElementsByName('payment[method]');
for (var i = 0; i < options.length; i++) {
if ($(options[i].id).checked) {
if (options[i].id.indexOf("tco") != -1) {
var params = Form.serialize('one-step-checkout-form');
var request = new Ajax.Request(
'<?php echo $this->getCheckoutUrl() . 'isAjax/tco'; ?>',
{
method: 'post',
onComplete: this.onComplete,
onSuccess: function(transport) {
if (transport.status == 200) {
if (transport.responseText.isJSON) {
var response = JSON.parse(transport.responseText);
$('onestepcheckout-place-order-loading').style.display = 'none';
$('checkout-' + response.update_section.name + '-load').update(response.update_section.html);
$('onestepcheckout-button-place-order').removeAttribute('onclick');
$('onestepcheckout-button-place-order').observe('click', formsubmit());
$('onestepcheckout-button-place-order').disabled = false;
}
}
},
onFailure: '', //checkout.ajaxFailure.bind(checkout),
parameters: params
});
} else if (options[i].id.indexOf("wirecard") != -1) {
var params = Form.serialize('one-step-checkout-form');
var request = new Ajax.Request(
'<?php echo $this->getCheckoutUrl() . 'isAjax/wirecard'; ?>',
{
method: 'post',
onComplete: this.onComplete,
onSuccess: function(transport) {
var response = JSON.parse(transport.responseText);
if (response.url) {
window.location.href = response.url;
} else {
var payment_method = $RF(form, 'payment[method]');
var wireparams = {'paymentMethod': payment_method};
url = '<?php echo Mage::getBaseUrl() . 'wirecard_checkout_page/processing/wirecard_checkout_pagecheckout/'; ?>';
var wirerequest = new Ajax.Request(
qmoreIsIframe,
{
method: 'get',
parameters: wireparams,
onSuccess: function(innerTransport) {
if (innerTransport && innerTransport.responseText) {
try {
var innerResponse = eval('(' + innerTransport.responseText + ')');
}
catch (e) {
innerResponse = {};
}
if (innerResponse.isIframe)
{
toggleQMoreIFrame();
$('qmore-iframe').src = url;
} else {
window.location.href = url;
}
}
},
onFailure: ''
});
}
},
onFailure: '', //checkout.ajaxFailure.bind(checkout),
parameters: params
});
} else {
if(isUseAmazon() == false){
$('one-step-checkout-form').submit();
}
else{
<?php
if(Mage::helper('core')->isModuleEnabled('Amazon_Payments')){
$helperAmz = new Amazon_Payments_Helper_Data();
if(isset($helperAmz))
$checkoutUrl = $helperAmz->getCheckoutUrl(false);
}
?>
window.location.href = "<?php if(isset($checkoutUrl)) echo $checkoutUrl;?>";
}
}
break;
}
}
}
}
}
}
function checkAjax(url) {
var form = $('one-step-checkout-form');
var payment_method = $RF(form, 'payment[method]');
var shipping_method = $RF(form, 'shipping_method');
var parameters = {
payment: payment_method,
shipping_method: shipping_method
}
get_billing_data(parameters);
get_shipping_data(parameters);
if ($('giftmessage-type') && $('giftmessage-type').value != '') {
parameters[$('giftmessage-type').name] = $('giftmessage-type').value;
}
if ($('create_account_checkbox_id') && $('create_account_checkbox_id').checked) {
parameters['create_account_checkbox'] = 1;
}
if ($('gift-message-whole-from') && $('gift-message-whole-from').value != '') {
parameters[$('gift-message-whole-from').name] = $('gift-message-whole-from').value;
}
if ($('gift-message-whole-to') && $('gift-message-whole-to').value != '') {
parameters[$('gift-message-whole-to').name] = $('gift-message-whole-to').value;
}
if ($('gift-message-whole-message') && $('gift-message-whole-message').value != '') {
parameters[$('gift-message-whole-message').name] = $('gift-message-whole-message').value;
}
if ($('billing-address-select') && $('billing-address-select').value != '') {
parameters[$('billing-address-select').name] = $('billing-address-select').value;
}
if ($('shipping-address-select') && $('shipping-address-select').value != '') {
parameters[$('shipping-address-select').name] = $('shipping-address-select').value;
}
new Ajax.Request(url, {
method: 'post',
evalJS: 'force',
onSuccess: function(transport) {
// alert(JSON.parse(transport.responseText).url);
if (JSON.parse(transport.responseText).url == 'null' || JSON.parse(transport.responseText).url == null) {
$('ajaxcart-loading').style.display = 'block';
$('ajaxcart-loading').style.top = '15%';
$('ajaxcart-loading').style.left = '40%';
$('ajaxcart-loading').style.width = '551px';
$('ajaxcart-loading').style.height = '400px';
$('ajaxcart-loading').style.overflow = 'hidden';
$('ajaxcart-loading').style.padding = '5px';
$('ajaxcart-loading').innerHTML = JSON.parse(transport.responseText).html;
$('iframe-warning').style.textAlign = 'left';
}
else
{
window.location.href = JSON.parse(transport.responseText).url;
}
},
onFailure: function(transport) {
},
parameters: parameters
});
}
I think I have to put the url in this function, but where and how, I don't understand. So please help me
You can always use the getOrderPlaceRedirectUrl() In your payment module Model and return your url to redirect customer to external page.
An other alternative could be to use the authorize() and trig a curl to the external url.

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

Uncaught SyntaxError: Unexpected token < (anonymous function) on console

I am creating an upload file application. I wrote it using AJAX and PHP.
It is working fine on the localhost but when I uploaded it to my web server. It returns the error:
Uncaught SyntaxError: Unexpected token <
It is pointing to the line
uploaded = JSON.parse(this.response);
This line is in my upload.js script file
upload.js
var app = app || {};
(function (obj) {
"use stricts;"
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 obj.options.finished === 'function') {
obj.options.finished(uploaded);
}
}else{
if (typeof obj.options.error === 'function') {
obj.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress',function(){
var percent;
if (event.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', obj.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 (obj.options.progressBar !== undefined) {
obj.options.progressBar.style.width = value ? value + '%': 0;
}
if (obj.options.progressText !== undefined) {
obj.options.progressText.innerText = value ? value + '%' : 0;
}
};
obj.uploader = function(options){
obj.options = options;
if (obj.options.files !== undefined) {
ajax(getFormData(obj.options.files.files));
}
}
}(app));
Here are the other codes for reference
upload.php
<?php
header('Content-Type: application/JSON');
$uploaded = [];
$allowed = ['jpg'];
$succeeded = [];
$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 (in_array($ext,$allowed) === true && move_uploaded_file($temp, "uploads/{$file}") === true) {
$succeeded [] = array('name' => $name, 'file' => $file);
# code...
}else{
$failed[] = array('name' => $name );
}
}else{
echo "Error";
}
}
}
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeeded' => $succeeded,
'failed' =>$failed
));
}
?>
and here's my html form
index.php
<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="button" id="submit" value="Upload">
</fieldset>
<div class="bar">
<span class="barfill" id="pb"><span class="barfilltext" id="pt">40%</span></span>
</div>
<div id="uploads" class="uploads">
</div>
<script type="text/javascript" src="upload.js"></script>
<script type="text/javascript">
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>The following files failed to upload</p>'
}
uploads.innerText = '' ;
anchor = document.createElement('p');
anchor.innerText = "Upload Completed!";
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);
uploads.appendChild(failed);
},
error: function (){
console.log("Error");
}
});
});
</script>
</form>
This code works on the localhost. It is uploading the files to my localhost server and shows the loading progressbar.
But when I deploy this to my web server it shows the progressbar loading slowly until it reaches 100%. But when I look into the uploads directory in my server nothing was uploaded.
you have a missing } at the end of the code in upload.php, before the php end (?>):
'failed' =>$failed
));
}
}
?>

Categories

Resources