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

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

Related

How to know if the do_upload is already started and done?

I'm using CodeIgniter, and I created a form where the user can upload a video. I wanted to create a progress bar to show the user its still uploading and hides it after the upload is done. What I wanted to do is when the submit button is click it will call my loading gif and i want it to keep loading until the upload is finished. How can i detect if the upload is finish?
CSS
<?php echo form_open_multipart('video_controller/video_form');?>
<div class="form-group">
<label for="title">Video</label>
<input type="file" accept=".mp4" class="form-control" name="video_field" placeholder="Video"></input>
</div>
<button class="btn btn-success pull-right" type="submit" value="upload" id="btn-submit">Create</button>
<?php echo form_close();?>
CodeIgniter
public function video_form(){
if (empty($_FILES['video_field']['name'])){
$this->form_validation->set_rules('video_file', 'Video File', 'required');
}
if($this->form_validation->run() == FALSE){
.....
}else{
$uploaderror = "";
$video_info = $this->upload_videos();
.....
Insert query code here
.....
}
}
private function upload_videos(){
$config = array();
$config['upload_path'] = './uploads/videos/';
$config['allowed_types'] = 'mp4';
$this->load->library('upload', $config);
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('video_field'))
{
$error_msg = $this->upload->display_errors('','');
error_log('UPLOAD ERROR: '.$error_msg);
if($error_msg!='You did not select a file to upload.'){
$filename = array('error' =>$error_msg.'('. $this->input->post('video_field') .')');
}
}
else
{
$vid = $this->upload->data();
$filename = array('video_field' =>$vid['file_name']);
}
return $filename;
}
You can use change event, XMLHttpRequest.upload.progress event
html
<input type="file" /><progress min="0" max="0" value="0"></progress>
javascript
var progress = $("progress");
$(":file").change(function(e) {
var file = e.target.files[0];
progress.val(0);
var request = new XMLHttpRequest();
if (request.upload) {
request.upload.onprogress = function(event) {
if (progress.val() == 0) {
progress.attr("max", event.total)
}
if (event.lengthComputable) {
// show `.gif` or update `progress` value here
// if `event.loaded` === `event.total`
// set `.gif` `display` to `none`
console.log(event.loaded, event.total);
progress.val(event.loaded)
}
}
request.onload = function() {
// do stuff with response
}
};
request.open("POST", "/path/to/server/");
request.send(file)
});
jsfiddle https://jsfiddle.net/576wrxLg/
i did the same in my codeigniter project with this code in JS..
i am 100% sure this will work for you. :)
$('#importForm').submit(function(e) {
var formData = new FormData(this);
$.ajax({
type:'POST',
url: base_url + "student/importAjax",
data:formData,
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
cache:false,
contentType: false,
processData: false,
dataType : "json",
success:function(data){
//console.log(data);
}
});
e.preventDefault();
});
function progress(e){
if(e.lengthComputable){
var max = e.total;
var current = e.loaded;
var Percentage = (current * 100)/max;
console.log(Percentage);
$('#progress-bar').css('width',Percentage+'%');
$('.sr-only').html(Percentage+'%');
if(Percentage >= 100)
{
// process completed
}
}
}
and this is my view (Bootstrap theme)
<form name="importForm" id="importForm" enctype="multipart/form-data">
<?php //echo form_open_multipart('admin/upload/do_upload'); ?>
<div class="box-body">
<div class="form-group">
<label for="exampleInputFile">Select File</label>
<input type="file" id="importInputFile" name="importInputFile" />
<p class="help-block">.xls / xlsx </p>
</div>
<div class="form-group">
<input type="checkbox" name="mid_term" class="check"><label style="margin-left: 10px;"> Mid Term User</label>
</div>
<div class="progress progress-sm active">
<div style="width:0%" aria-valuemax="100" aria-valuemin="0" aria-valuenow="20" role="progressbar" id="progress-bar" class="progress-bar progress-bar-success progress-bar-striped">
<span class="sr-only"></span>
</div>
</div>
<div class="box-footer">
<button class="btn btn-primary" id="ajaxImportUpload" type="submit">Submit</button>
</div>
</div>
</form>
my Controller
public function importAjax() {
$upload_path = './uploads/';
$newname = rand(0000, 9999) . basename($_FILES["importInputFile"]["name"]);
$target_file = $upload_path . $newname;
$filename = $newname;
$filenameArray = explode(".", $filename);
$extension = end($filenameArray);
if ($extension == 'xlsx' || $extension == 'xls') {
if (move_uploaded_file($_FILES["importInputFile"]["tmp_name"], $target_file)) {
// echo "The file ".$newname . " has been uploaded.";
} else {
//echo "Sorry, there was an error uploading your file.";
}
$this->load->library('Excel');
$csvData = $this->excel->parseFile($target_file, false);
$fileType = 'Excel';
} else {
echo json_encode(array('error' => true, 'msg' => 'xlsx and xls are allowed extnsion'));
return false;
}
array_shift($csvData);
$user = array();
if (isset($_POST['mid_term']) && $_POST['mid_term'] == 'on') {
$mid_term = 1;
} else {
$mid_term = 0;
}
$insertedCount=0;
$totalCount=0;
foreach ($csvData as $studentData) {
$totalCount++;
$id = $this->StudentModel->checkImportSchool($studentData[2]);
$cid = $this->StudentModel->checkImportclass($studentData[7]);
$sid = $this->StudentModel->checkImportStudentUsername($studentData[0]);
if ($id > 0 && $sid=="notFound") {
$fullname = explode(" ", $studentData[1]);
if (isset($fullname[1]) == '')
$middlename = '';
else
$middlename = $fullname[1];
if (isset($fullname[2]) == '')
$lastname = '';
else
$lastname = $fullname[2];
$user['username'] = $studentData[0];
$user['firstname'] = $fullname[0];
$user['middlename'] = $middlename;
$user['lastname'] = $lastname;
$user['phone'] = $studentData[3];
$user['email'] = $studentData[4];
$password_salt = substr(sha1(uniqid(rand(), true)), 1, 20);
$password = md5($studentData[5] . $password_salt);
$parentPassword = md5($studentData[6] . $password_salt);
$user['password'] = $password;
$user['parentPassword'] = $parentPassword;
$user['password_salt'] = $password_salt;
$user['mid_term'] = $mid_term;
$user['userType'] = 'student';
$school = $id;
$class = $cid;
$this->StudentModel->importFromExcel($user, $class, $school);
$insertedCount++;
}
else {
$skipData[]=$studentData;
}
}
unlink($target_file);
if(!empty($skipData)){
$this->session->set_userdata(array('item'=>$skipData));
}
else{
$skipData=array();
}
$skipDataCount=count($skipData);
echo json_encode(array('error' => false, 'msg' => 'Data Inserted Successfully','skipData'=>$skipData,'insertedCount'=>$insertedCount,'skipDataCount'=>$skipDataCount,'totalCount'=>$totalCount));
}

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.

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

SyntaxError: Unexpected token l in ajax call

I am trying to fetch a data from the server data base and pass it to the ajax to create a database table and its data in the local android database. But when an ajax call is make it give following error.
LogCat:
01-30 10:58:45.888: D/CordovaLog(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l
01-30 10:58:45.888: I/Web Console(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l at file:///android_asset/www/home.html:513
here is the ajax code:
$.ajax({
url : urlServer + 'getTableData.php',
// type: 'POST',
contentType : 'application/json',
beforeSend : function() {
$.mobile.loading('show')
},
complete : function() {
console.log("ajax complete");
createTable();
},
dataType : 'json',
data : {userId: user_id},
success : function(data) {
if (data != null)
{
dynamic_tabledetails = data.Table_details;
dynamic_selectQuery = data.SelectTableQuery;
table_data = data;
getTabledetails(dynamic_tabledetails);
}
else
{
alert("Error Message");
}
},
error : function(xhr, ajaxOptions, thrownError) {
console.log("Server is not responding... Please try again: "+thrownError);
}
});
Here is the php code:
<?php
require_once ('connect.php');
$userID= $_REQUEST['userId'];
$data = array ();
$listtables = array();
$Tabledetails = array();
$select_table = '';
$tab_name = array();
$getlistTables = 'SHOW TABLES FROM sacpl_crm_dev ';
$resultsListTables = mysql_query($getlistTables);
echo 'length of the tables name: '.$resultsListTables.' ';
while ($row = mysql_fetch_array($resultsListTables))
{
if(strpos($row[0],'_trail') == false)
{
$temporarydata = array();
$TableName = new ArrayObject();
$getTabledetails = 'show columns from '.$row[0].'';
$resultdetails = mysql_query($getTabledetails);
$TableName['tablename'] = $row[0];
$tab_name[] =$row[0];
$column = array();
$delete_field = '';
$comp_codeField = '';
while($rows = mysql_fetch_array($resultdetails))
{
$column_list =new ArrayObject();
$column_list['FieldName'] = $rows['Field'];
$column_list['Default'] = $rows['Default'];
if(strpos($rows['Type'],'(') == false)
{
$column_list['dataType'] = $rows['Type'];
$column_list['dataType_limit'] ='';
}
else
{
$type = explode('(',$rows['Type']);
$column_list['dataType'] = $type[0];
$column_list['dataType_limit'] = '('.$type[1];
}
if($rows['Field'] == 'deleted')
{
$delete_field = 'deleted = 0';
}
if($rows['Field'] == 'userId')
{
$userIdField = $rows['Field'].'="'.$userId.'"';
}
$column_list['Extra'] = $rows['Extra'];
$column_list['Null_value'] = $rows['Null'];
$column_list['Key_value'] = $rows['Key'];
$column[] = $column_list;
}
$TableName['column_details'] = $column;
$Tabledetails[]=$TableName;
if($userIdField == '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$delete_field.'';
}
else if($userIdField != '' && $delete_field =='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.'';
}
else if($userIdField != '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.' and '.$delete_field.'';
}
else{
$select_table = 'select * from '.$row[0].'';
}
$select_query[] = $select_table;
$resultTableData = mysql_query($select_table);
while ($row1 = mysql_fetch_array($resultTableData))
{
$temporarydata[] = $row1;
}
$data[$row[0]] = $temporarydata;
}
}
$data['Table_details'] = $Tabledetails;
$data['SelectTableQuery'] = $select_query;
mysql_close($con);
require_once('JSON.php');
$json = new Services_JSON();
echo ($json->encode($data));
?>
Comment out the line:
echo 'length of the tables name: '.$resultsListTables.' ';
Also, when outputting JSON for an AJAX call, it's important to set the Content-type header using:
header('Content-type: application/json; charset=utf-8',true);
This php code doesn't seem to have syntax error. the problem probably lies on the included php's: "connect.php" and "JSON.php". could you please post them too so we can find the error.
Link this into the beginning of your PHP-file:
header("Content-Type: text/javascript; charset=utf-8");

Categories

Resources