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

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

Related

Value is not passing through Javascript it directly goes to PHP

I'm trying to pass a file and some text field and a drop down value to php in order to upload them all in a query in database. I'm validating the text field input in JavaScript to prevent giving any wrong input. But the problem is the values are not going through JavaScript all the time. So i've set the php file in form action. So now what is happening that, it is not checking individual text field input and not showing error. Rather goes direct to the php. Now how can i resolve this
HTML
<form id="jobform" class="form-horizontal" method="post" action="test.php" enctype="multipart/form-data">
<h2><b>Post your job</b></h2><br><br>
<div class="form-group">
<label class="control-label col-sm-2">Job Position:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="jName" placeholder="Enter job name" name="jName" required>
<p id="jErr"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Job Salary:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="sal" placeholder="Enter job salary" name="sal" required>
<p id="salErr"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Job Type:</label>
<div class="col-sm-10">
<div class="dropdown">
<select id="jType">
<option value="part-time">Part-Time</option>
<option value="full-time">Full-Time</option>
<option value="internship">Internship</option>
</select>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Job Location:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="loc" placeholder="Enter job locations" name="loc" required>
<p id="locErr"></p>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2">Add some detailed description:</label>
<div class="col-sm-10">
<input id="u_file" value="u_file" type="file" name="u_file" size="5000000" multiple onchange="showname()"><br><br>
</div>
</div>
<div class="container-fluid text-center">
<br><button name="submitJob" id="submitJob" type="submit" class="btn btn-default" onclick="job_checker()">Submit</button>
<p id="submitJobErr"></p></div>
</form>
JavaScript
signFlagj = 0;
function job_checker() {
checkJobName();
checkSalary();
checkJobType();
checkJobLoc();
databasejobEntry();
}
function checkJobName() {
jobnameET = document.getElementById("jName");
var jobnameError = document.getElementById("jErr");
jobname = jobnameET.value;
console.log(jobname);
var regex = /^[a-zA-Z ]*$/;
if(!regex.test(jobname)){
jobnameError.innerHTML = "Only letters and white space allowed";
signFlagj = 1;
}
else {
jobnameError.innerHTML = "";
}
}
function checkSalary() {
var salaryET = document.getElementById("sal");
var salaryError = document.getElementById("salErr");
jobsal = salaryET.value;
console.log(jobsal);
var regex = /^[1-9.,][0-9.,]*$/;
if(!regex.test(jobsal)){
salaryError.innerHTML = "Only numbers with or without comma or point is allowed";
signFlagj = 1;
}
else {
salaryError.innerHTML = "";
}
}
function checkJobType() {
var jobTypeET = document.getElementById("jType");
jobType = jobTypeET.value;
console.log(jobType);
}
function checkJobLoc() {
var jobLocET = document.getElementById("loc");
var locError = document.getElementById("locErr");
jobLocation = jobLocET.value;
console.log(jobLocation);
var regex = /^[a-zA-Z0-9\/\s,'-]*$/;
if(!regex.test(jobLocation)){
locError.innerHTML = "Enter valid amount";
signFlagj = 1;
}
else {
locError.innerHTML = "";
}
}
function showname() {
jobFilename = document.getElementById('u_file');
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log('Selected file: ' + jobFilename.files.item(0).size);
console.log('Selected file: ' + jobFilename.files.item(0).type);
}
/*function toSubmit(){
preventDefault();
alert('I will not submit');
return false;
}*/
function databasejobEntry() {
if(signFlagj==1) {
console.log("fill up correctly!");
alert("Sign up correctly!");
window.location.href = "test.html";
}
else
{
// console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log(jobname);
var submitError = document.getElementById("submitJobErr");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
console.log(response);
submitError.innerHTML=response;
alert(response);
if(String(response.trim()) === "Success") {
alert("Successfully submitted :)");
var formdata = $('#jobform').serializeArray();
//alert(formdata);
document.getElementById("jobform").submit();
//window.location.href = "uploadJob.html";
}
}
}
xhttp.open("POST", "test.php?jobname="+jobname+"&jobType="+jobType+"&jobsal="+jobsal+"&jobLocation="+jobLocation+"&jobFilename="+jobFilename,true);
//xhttp.open("POST", "three.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xhttp.open("POST", "test.php?jobname="+jobname+"&jobFilename="+jobFilename,true);
xhttp.send();
}
}
PHP
<?php
require_once('DBconnection.php');
//ini_set('display_errors', 1);
//ini_set('log_errors', 1);
$val="";
$jobName = $_POST["jName"];
$jobType = $_POST["jType"];
$jobSalary = $_POST["sal"];
$jobLocation = $_POST["loc"];
echo "$jobName";
echo "$jobType";
echo "$jobSalary";
echo "$jobLocation";
//print_r($jobName);
echo"<br>";
//$u_file = $_FILES['jobFilename'];
$file_type = $_FILES['u_file']['type'];
$file_size = $_FILES['u_file']['size'];
$file_name = $_FILES['u_file']['name'];
//echo "$jobName";
print_r($file_name);
echo"<br>";
print_r($file_size);
echo"<br>";
print_r($file_type);
echo"<br>";
//echo "****************";
$currentdir = getcwd();
$targetfolder = $currentdir . "/testupload/";
// echo "****************";
print_r($targetfolder);
$targetfile = $targetfolder . basename( $_FILES['u_file']['name']) ;
print_r($targetfile);
//print_r($currentdir);
//echo "****************";
$uploadOk=1;
//print_r($file_type);
//echo "The file ". basename( $_FILES['u_file']['name']). " is uploaded";
if ($file_type != "application/pdf" && $file_type != "image/png" && $file_type != "image/jpeg" && $file_type != "image/jpg") {
echo "Sorry, only JPG, JPEG, PNG & PDF files are allowed.";
$uploadOk = 0;
}
if (file_exists($targetfile)) {
echo "Sorry, file already exists.";
$uploadOk = 0;
}
if($uploadOk==0){
echo "Problem in uploading file";
}
else {
if(move_uploaded_file($_FILES['u_file']['tmp_name'], $targetfile)) {
$fileUpQueryjob = "INSERT INTO jobs (job_name,job_type,job_salary,job_location,job_filename) VALUES ('$jobName','$jobType','$jobSalary','$jobLocation','$file_name')";
$upJob = $db->query($fileUpQueryjob);
if ($upJob == true) {
$val = "Success";
echo "The file ". basename( $_FILES['u_file']['name']). " is uploaded";
}
else
echo "Error: " . $fileUpQueryjob . "<br>" . mysqli_error($db);
}
}
//echo "$val";
$db->close();
?>
It may be due to the fact that your button type is 'sumbit' and its taking preference over the onlick. So cleanest way, remove submit type, and manually submit after validation:
<button name="submitJob" id="submitJob" class="btn btn-default" onClick="job_checker()">Submit</button>
Find your DOM form on your "validating" function, and submit it if all is ok:
function job_checker() {
// just refactor all these functions to return "true" or "false"
var isValid = checkJobName() &&
checkSalary() &&
checkJobType() &&
checkJobLoc() &&
databasejobEntry();
// if all these validations went through,
if (isValid) {
document.querySelector('#jobForm').submit();
}
}
There are errors in your javascript. Try this:
JAVASCRIPT
signFlagj = 0;
function job_checker()
{
checkJobName();
checkSalary();
checkJobType();
checkJobLoc();
databasejobEntry();
}
function checkJobName()
{
var jobnameET = document.getElementById("jName");
var jobnameError = document.getElementById("jErr");
var jobname = jobnameET.value;
console.log(jobname);
var regex = /^[a-zA-Z ]*$/;
if(!regex.test(jobname))
{
jobnameError.innerHTML = "Only letters and white space allowed";
signFlagj = 1;
}
else jobnameError.innerHTML = "";
}
function checkSalary()
{
var salaryET = document.getElementById("sal");
var salaryError = document.getElementById("salErr");
var jobsal = salaryET.value;
console.log(jobsal);
var regex = /^[1-9.,][0-9.,]*$/;
if(!regex.test(jobsal))
{
salaryError.innerHTML = "Only numbers with or without comma or point is allowed";
signFlagj = 1;
}
else salaryError.innerHTML = "";
function checkJobType()
{
var jobTypeET = document.getElementById("jType");
var jobType = jobTypeET.value;
console.log(jobType);
}
function checkJobLoc()
{
var jobLocET = document.getElementById("loc");
var locError = document.getElementById("locErr");
var jobLocation = jobLocET.value;
console.log(jobLocation);
var regex = /^[a-zA-Z0-9\/\s,'-]*$/;
if(!regex.test(jobLocation))
{
locError.innerHTML = "Enter valid amount";
signFlagj = 1;
}
else locError.innerHTML = "";
}
function showname()
{
var jobFilename = document.getElementById('u_file');
console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log('Selected file: ' + jobFilename.files.item(0).size);
console.log('Selected file: ' + jobFilename.files.item(0).type);
}
/*
function toSubmit()
{
preventDefault();
alert('I will not submit');
return false;
}
*/
function databasejobEntry()
{
if(signFlagj==1)
{
console.log("fill up correctly!");
alert("Sign up correctly!");
window.location.href = "test.html";
}
else
{
// console.log('Selected file: ' + jobFilename.files.item(0).name);
console.log(jobname);
var submitError = document.getElementById("submitJobErr");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
console.log(this.readyState);
if(this.readyState == 4 && this.status == 200)
{
console.log(this.status);
var response = xhttp.responseText;
console.log(response);
submitError.innerHTML=response;
alert(response);
if(String(response.trim()) === "Success")
{
alert("Successfully submitted :)");
var formdata = $('#jobform').serializeArray();
//alert(formdata);
document.getElementById("jobform").submit();
//window.location.href = "uploadJob.html";
}
}
}
xhttp.open("POST", "test.php?jobname="+jobname+"&jobType="+jobType+"&jobsal="+jobsal+"&jobLocation="+jobLocation+"&jobFilename="+jobFilename,true);
//xhttp.open("POST", "three.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xhttp.open("POST", "test.php?jobname="+jobname+"&jobFilename="+jobFilename,true);
xhttp.send();
}
}
PHP
<?php
require_once('DBconnection.php');
// ...
// Since you are using a database connection consider using a function
// to escape strings like mysli_real_escape_string() if you are using MySQL
$jobName = $_POST["jName"];
$jobType = $_POST["jType"];
$jobSalary = $_POST["sal"];
$jobLocation = $_POST["loc"];
?>

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.

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

Creating export and import in codeigniter i need an assistant

I need an assistant with creating export and import file in codeigniter, I am not advanced in coding, I am still learning. I didn't add export button as I also need an assistant on how to add it
Here is my view
<form method="post" action="<?php echo base_url() ?>csv/importcsv" enctype="multipart/form-data">
<input type="file" name="userfile" size="10" style="width:20px;">
<input type="submit" name="submit" value="IMPORT" class="btn btn-primary">
</form>
Here is my controller
/****MANAGE MEMBERS*****/
function member($param1 = '', $param2 = '', $param3 = '') {
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
if ($param1 == 'create') {
$data['names'] = $this->input->post('names');
$data['surname'] = $this->input->post('surname');
$data['title'] = $this->input->post('title');
$data['initials'] = $this->input->post('initials');
$data['id_number'] = $this->input->post('id_number');
$data['passport'] = $this->input->post('passport');
$data['birthdate'] = $this->input->post('birthdate');
$data['gender'] = $this->input->post('gender');
$data['email'] = $this->input->post('email');
$data['address_1'] = $this->input->post('address_1');
$data['address_2'] = $this->input->post('address_2');
$data['address_3'] = $this->input->post('address_3');
$data['province'] = $this->input->post('province');
$data['country'] = $this->input->post('country');
$data['postal_code'] = $this->input->post('postal_code');
$data['phone'] = $this->input->post('phone');
$data['tel'] = $this->input->post('tel');
$data['country'] = $this->input->post('country');
$data['region'] = $this->input->post('region');
$data['branch'] = $this->input->post('branch');
$data['creation_timestamp'] = $this->input->post('creation_timestamp');
$data['expiry_timestamp'] = $this->input->post('expiry_timestamp');
$data['beneficiary_name'] = $this->input->post('beneficiary_name');
$data['beneficiary_surname'] = $this->input->post('beneficiary_surname');
$data['beneficiary_id_number'] = $this->input->post('beneficiary_id_number');
$data['beneficiary_phone'] = $this->input->post('beneficiary_phone');
$data['message'] = $this->input->post('message');
$data['chat_status'] = $this->input->post('chat_status');
$this->db->insert('member', $data);
$member_id = mysql_insert_id();
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/member_image/' . $member_id . '.jpg');
$this->email_model->account_opening_email('member', $data['email']); //SEND EMAIL ACCOUNT OPENING EMAIL
redirect(base_url() . 'index.php?admin/member/', 'refresh');
}
if ($param1 == 'do_update') {
$data['names'] = $this->input->post('names');
$data['surname'] = $this->input->post('surname');
$data['title'] = $this->input->post('title');
$data['initials'] = $this->input->post('initials');
$data['id_number'] = $this->input->post('id_number');
$data['passport'] = $this->input->post('passport');
$data['birthdate'] = $this->input->post('birthdate');
$data['gender'] = $this->input->post('gender');
$data['email'] = $this->input->post('email');
$data['address_1'] = $this->input->post('address_1');
$data['address_2'] = $this->input->post('address_2');
$data['address_3'] = $this->input->post('address_3');
$data['province'] = $this->input->post('province');
$data['country'] = $this->input->post('country');
$data['postal_code'] = $this->input->post('postal_code');
$data['phone'] = $this->input->post('phone');
$data['tel'] = $this->input->post('tel');
$data['country'] = $this->input->post('country');
$data['region'] = $this->input->post('region');
$data['branch'] = $this->input->post('branch');
$data['creation_timestamp'] = $this->input->post('creation_timestamp');
$data['expiry_timestamp'] = $this->input->post('expiry_timestamp');
$data['beneficiary_name'] = $this->input->post('beneficiary_name');
$data['beneficiary_surname'] = $this->input->post('beneficiary_surname');
$data['beneficiary_id_number'] = $this->input->post('beneficiary_id_number');
$data['beneficiary_phone'] = $this->input->post('beneficiary_phone');
$data['message'] = $this->input->post('message');
$data['chat_status'] = $this->input->post('chat_status');
$this->db->where('member_id', $param2);
$this->db->update('member', $data);
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/member_image/' . $param2 . '.jpg');
redirect(base_url() . 'index.php?admin/member/', 'refresh');
} else if ($param1 == 'personal_profile') {
$page_data['personal_profile'] = true;
$page_data['current_member_id'] = $param2;
} else if ($param1 == 'edit') {
$page_data['edit_data'] = $this->db->get_where('member', array(
'member_id' => $param2
))->result_array();
}
if ($param1 == 'delete') {
$this->db->where('member_id', $param2);
$this->db->delete('member');
redirect(base_url() . 'index.php?admin/member/', 'refresh');
}
$page_data['teachers'] = $this->db->get('member')->result_array();
$page_data['page_name'] = 'member';
$page_data['page_title'] = get_phrase('manage_member');
$this->load->view('index', $page_data);
if (!this->load->importcsv()); {
$data['memberbook'] = $this->csv_model->get_memberbook();
$data['error'] = ''; //initialize image upload error array to empty
$config['upload_path'] = './uploads/';
$config['allowed_types'] = 'csv';
$config['max_size'] = '1000';
$this->load->library('upload', $config);
// If upload failed, display error
if (!$this->upload->do_upload()) {
$data['error'] = $this->upload->display_errors();
$this->load->view('index', $data);
} else {
$file_data = $this->upload->data();
$file_path = './uploads/'.$file_data['file_name'];
if ($this->csvimport->get_array($file_path)) {
$csv_array = $this->csvimport->get_array($file_path);
foreach ($csv_array as $row) {
$insert_data = array(
'names'=>$row['names'],
'surname'=>$row['surname'],
'initials'=>$row['initials'],
'id_number'=>$row['id_number'],
'passport'=>$row['passport'],
'birthdate'=>$row['birthdate'],
'gender'=>$row['gender'],
'phone'=>$row['phone'],
'email'=>$row['email'],
'address_1'=>$row['address_2'],
'address_2'=>$row['address_2'],
'address_3'=>$row['address_3'],
'province'=>$row['province'],
'country'=>$row['country'],
'postal_code'=>$row['postal_code'],
'tel'=>$row['tel'],
'region'=>$row['region'],
'branch'=>$row['branch'],
'creation_timestamp'=>$row['creation_timestamp'],
'expiry_timestamp'=>$row['expiry_timestamp'],
'beneficiary_name'=>$row['beneficiary_name'],
'beneficiary_surname'=>$row['beneficiary_surname'],
'beneficiary_id_number'=>$row['beneficiary_id_number'],
'beneficiary_phone'=>$row['beneficiary_phone'],
'message'=>$row['message'],
);
$this->csv_model->insert_csv($insert_data);
}
$this->session->set_flashdata('success', 'Csv Data Imported Succesfully');
redirect(base_url().'csv');
//echo "<pre>"; print_r($insert_data);
} else
$data['error'] = "Error occured";
$this->load->view('csvindex', $data);
}
}
}
After months with this problem i came up a solution so i thought i should share it for some peeps who are having same difficulties
CONTROLLER
function member_bulk_add($param1 = '')
{
if ($this->session->userdata('admin_login') != 1)
redirect(base_url(), 'refresh');
if ($param1 == 'import_excel')
{
move_uploaded_file($_FILES['userfile']['tmp_name'], 'uploads/import.xlsx');
// Importing excel sheet for bulk student uploads
include 'simplexlsx.php';
$xlsx = new SimpleXLSX('assets/import.xlsx');
list($num_cols, $num_rows) = $xlsx->dimension();
$f = 0;
foreach( $xlsx->rows() as $r )
{
// Ignore the inital name row of excel file
if ($f == 0)
{
$f++;
continue;
}
for( $i=0; $i < $num_cols; $i++ )
{
if ($i == 0) $data['name'] = $r[$i];
else if ($i == 1) $data['birthday'] = $r[$i];
else if ($i == 2) $data['sex'] = $r[$i];
else if ($i == 3) $data['address'] = $r[$i];
else if ($i == 4) $data['phone'] = $r[$i];
else if ($i == 5) $data['email'] = $r[$i];
}
$data['member_id'] = $this->input->post('member_id');
$this->db->insert('member' , $data);
//print_r($data);
}
redirect(base_url() . 'index.php?admin/member/' . $this->input->post('member_id'), 'refresh');
$this->load->view('backend/index', $page_data);
}

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