Jquery file uploading JSON empty error - javascript

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.

Related

php list files in directory and save to disk

I want to list the files in "archives/" and write the decoded array to disk (file name = "archives/events.txt") But what I have doesn't create that file.
xhr.send(data); // gives: Uncaught ReferenceError: data is not defined
What am I doing wrong?
function LISTevents () {
var xhr = new XMLHttpRequest();
xhr.open("POST", "json-events.php");
xhr.onload = function () {
console.log(this.response);
};
xhr.send(data);
return false;
}
json-events.php
<?php
// create list of events files in archives/* on server
$files1 = scandir('archives');
file_put_contents('archives/events.txt', print_r($files1, true));
?>
<?php
function list_contents($dir, $suffix) {
$contents = array();
$dir = realpath($dir);
if (is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
if ($file != '.' && $file != '..' && $file != 'events.txt') {
if (substr($file, -strlen($suffix)) == $suffix) {
$contents[] = $file;
}
}
}
foreach ($contents as $key => $item) {
if (strlen($item) != 14) {
unset($contents[$key]);}
}
foreach ($contents as $key => $item) {
if (substr($item,0,1) != "2") {
unset($contents[$key]);}
}
}
$contents_json = json_encode($contents);
file_put_contents($dir . '/events.txt', $contents_json);
}
list_contents('archives','.txt');
?>

Uncaught Syntax Error: Unexpected end of input 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?

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
));
}
}
?>

Jquery ajax function fails with no reason

I have a web based mobile android application. I built it with php + jquery + mysql. An ajax code fails but no reason. Therefore it returns 'Try again'. Unfortunately I can not debug it in the application. Here is the code:
$('.get-order-button').live('click', function() {
var musteritel = $('#musteritel').val(), musteriad = $('#musteriad').val(), musteriadres = $('#musteriadres').val(), musterinotu = $('#siparisnotu').val(), odemesekli =$('#odemesekli option:selected').val() ;
if(musteritel != ''){
$.ajax({
type : 'POST',
url : '/enfes/temp-order-sent.php', timeout: 10000,
cache : false,
data : 'musteritel='+musteritel+'&musteriadres='+musteriadres+'&musterinotu='+musterinotu+'&odemesekli='+odemesekli+'&musteriad='+musteriad,
dataType : 'json',
beforeSend : function() {
showDialog('Yükleniyor...')
},
whileLoading: function(xhr) {
if (xhr && xhr.readyState != 4)
xhr.abort()
}
}).always(function() {
closeDialog()
}).fail(function() {
showToastShort('Try again.');
}).done(function(r) {
if(r.s==1){
$.each(r.u, function( index, value ) {
unsetMyCookie(index);
});
$('#detail').remove();
$('.basket-added-btn span').text('0');
basketStatus = 0;
showToastLong(r.m);
window.location.hash = 'home';
}else
showToastShort(r.m);
});
}
return false
});
And here is the php code:
<?php
session_start();
include_once 'class.render.php';
include_once 'class.order.php';
$kendim = new render();
if(isset($_SESSION["id"]) && isset($_POST['musteritel'])) {
$kendiId = $_SESSION["kendiId"];
$uniqueIdentifier = $_SESSION["uniqueIdentifier"];
if(isset($_COOKIE)){
$order = new order();
$musteritel = $order->validTel($_POST['musteritel']);
$musteriad = $order->cleanStr($_POST['musteriad']);
$musteriadres = $order->cleanStr($_POST['musteriadres']);
$musterinotu = $order->cleanStr($_POST['musterinotu']);
$odemesekli = $order->cleanStr($_POST['odemesekli']);
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
$ordersent = $order->addOrder($musteritel, $musteriad, $musteriadres, $musterinotu, $odemesekli);
if($musteritel == "") {
$return = array('s' => 1, 'm' => 'Telefon numaranızı hatalı girdiniz.');
} else {
if($ordersent){
$return = array('s' => 1, 'm' => 'Siparisiniz bize ulasmistir.', 'u' => $order->basket);
}else
$return = array('s' => 0, 'm' => 'Siparis gonderilemedi. Bilgilerinizi kontrol ediniz.');
}
}else
$return = array('s' => 0, 'm' => 'Siparis sepetiniz bos.');
}else
$return = array('s' => 0, 'm' => 'Telefon numaranızı yazmalisiniz.');
echo json_encode($return);
?>
Why does it fail?

Categories

Resources