Cannot read property 'removeChild' of null dropzone - javascript

I have this code:
CODE JS:
var currentFile = null;
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("div#myDrop", {
url : "<?php echo $this->serverUrl() . '/profile/ajax/dzupload'; ?>",
paramName : 'profilepicture',
acceptedFiles : "image/*",
maxFiles : 1,
addRemoveLinks : true,
init : function() {
var fileName = $('#profilePicture').val();
var mockFile = { name: fileName, size: 12345 };
this.options.addedfile.call(this, mockFile);
this.options.thumbnail.call(this, mockFile, "<?php echo $this->serverUrl().'/public/profile/'.'usr'.$practitionerInfo->user_id.'/picture/'.$practitionerInfo->profilepicture ?>");
currentFile = mockFile;
this.on("addedfile", function(file) {
if (currentFile) {
this.removeFile(currentFile);
}
currentFile = file;
});
this.on("success", function(file, responseText) {
$('#profilePicture').attr("value", responseText.filename);
console.log(responseText );
});
this.on("maxfilesexceeded", function(file){
this.removeFile(file);
alert("You are not allowed to chose more than 1 file!");
});
this.on("removedfile", function (file){
$.ajax({
method: 'POST',
url: '<?php echo $this->serverUrl() . '/profile/ajax/dzdelete' ?>',
data: {
area : 'company-profile',
name : $('#profilePicture').attr('value')
},
success: function(result){
$('#profilePicture').attr("value", '')
console.log(result);
}
})
});
}
});
ERROR:
Cannot read property 'removeChild' of null
What causes this error?
How can I solve it?
This error occurs when I get on the Upload function
It has never met anyone with such an error?How can I improve my code so that it only be this error?
Thanks in advance!

Replace the removedfile method to be like this
if ((_ref = file.previewElement) != null) {
//_ref.parentNode.removeChild(file.previewElement);
_ref.style.display = "none";
}
in file dropzone.js

Related

Getting stored images with Dropzone.js

I am trying getting the images stored at folder, but the when i am calling the images give 404 because of this:
http://localhost/xxxx/new/item/77/public/images/item/77/2.jpg
i don't no how to remove "new/item/77/" and get the image to the correct folder:
My javascript
$(".dropzone").dropzone({
init: function() {
myDropzone = this;
$.ajax({
url: 'image/get',
type: 'post',
data: {request: 'fetch'},
dataType: 'json',
success: function(response){
$.each(response, function(key,value) {
var mockFile = { name: value.name, size: value.size};
myDropzone.emit("addedfile", mockFile);
myDropzone.emit("thumbnail", mockFile, value.path);
myDropzone.emit("complete", mockFile);
});
}
});
}
});
My route
Route::post('new/item/{id}/image/get','ItemController#fileGet');
My Controller
public function fileGet(Request $request){
$fileList = [];
$targetDir= 'public/images/item/77/';
$dir = $targetDir;
if (is_dir($dir)){
if ($dh = opendir($dir)){
while (($file = readdir($dh)) !== false){
if($file != '' && $file != '.' && $file != '..'){
$file_path = $targetDir.$file;
if(!is_dir($file_path)){
$size = filesize($file_path);
$fileList[] = ['name'=>$file, 'size'=>$size, 'path'=>$file_path];
}
}
}
closedir($dh);
}
}
echo json_encode($fileList);
exit;
}
What i expect is
http://localhost/xxxx/public/images/item/77/2.jpg
Or if any one knows a better way to get the files stored in the dropzone.js
Thnaks!
$(".dropzone").dropzone({
init: function() {
Dropzone = this;
$.ajax({
url: APP_URL + '/image/get',
type: 'post',
dataType: 'json',
success: function(response){
$.each(response, function(key,value) {
var mockFile = { name: value.name, size: value.size};
Dropzone.options.addedfile.call(Dropzone, mockFile);
Dropzone.options.thumbnail.call(Dropzone, mockFile, APP_URL+"/"+value.path);
Dropzone.options.complete.call(Dropzone, mockFile);
});
}
});
}
});

Attach file with spaces in the name

I can't attach files with spaces in the name, but when have no space
is successfully attached, i'm using codeigniter for this,
uploading the file to the server before attach it, i use the helper Path for get the routes to my file.
function upload_file() {
//$this->load->helper('path');
//$path = set_realpath('./uploads/');
//upload file
$config['upload_path'] = './uploads/';
$config['allowed_types'] = '*';
$config['max_filename'] = '255';
$config['encrypt_name'] = FALSE;
$config['max_size'] = '50000';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
if (isset($_FILES['file']['name'])) {
if (0 < $_FILES['file']['error']) {
echo 'Error durante la carga' . $_FILES['file']['error'];
} else {
if (file_exists('./uploads/' . $_FILES['file']['name'])) {
echo 'Nombre de archivo ya existe : uploads/' . $_FILES['file']['name'];
} else {
$this->load->library('upload', $config);
if (!$this->upload->do_upload('file')) {
echo $this->upload->display_errors();
} else {
echo 'Archivo cargado! : ./uploads/' . $_FILES['file']['name'];
}
}
}
} else {
echo 'Porfavor selecciona un archivo';
}
}
Part of sendMail function:
$archivo = $_FILES['file']['name'];
$path = set_realpath('./uploads/');
$adjunto = $path.$archivo;
$this->email->attach($adjunto);
Part of the view and JS
<input type="file" id="file" name="file" />
$(document).ready(function (e) {
$('#file').on('change', function () {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://mail.mayordomus.cl/Cpersona/upload_file',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response);
},
error: function (response) {
$('#msg').html(response);
}
});
});
});
You can remove space characters from file name at client side using File constructor
let files = [new File([1], "file name.txt"), new File([2], "file name1.txt")];
let fd = new FormData();
for (let i = 0; i < files.length; i++) {
console.log(`Original file name: ${files[i].name}`);
let filename = files[i].name.replace(/\s/g, "-");
let file = new File([files[i].slice()], filename);
fd.append("files-" + i, file);
}
for (let [, prop] of fd) {
console.log(`FormData file name:${prop.name}`);
}

ajax running error despite response being 200

I have multiple uploads on a page, and I am workin on tidying it up, so:
Here's my js:
$(".img").change(function () {
var form = $(this).closest('form');
getPath(form);
})
deleteButton();
copyGalleryData();
});
function getPath(form) {
var name = $(form).attr('name');
submitImage(form, name);
}
var path_to_delete;
function submitImage(form, name) {
var url = '/image/upload';
var form_data = new FormData($(form)[0]);
submit(name);
form_data.append('img', $(form).children(".img"));
$.ajax({
url: url,
data: form_data,
dataType: 'json',
async: true,
type: 'post',
processData: false,
contentType: false,
success: function (data) {
console.log(data);
$(form).children('.image-container').append('<img id="image" name=' + name + '" src="' + data + '" />')
$(".imageDelete").attr('data', data);
alerts();
var deleting = false;
success(name, deleting, data);
$('.messages').html('<div class="alert alert-success">Image Uploaded!<div>');
},
error: function (data) {
alerts();
fail();
$('.messages').html('<div class="alert alert-danger">File type not supported! Use files with image extension only!</div>');
},
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
}
and controller:
class ImageController extends Controller
{
use S3;
public function upload(ImgRequest $request)
{
if ($request->hasFile('img')) {
$this->imageEntity();
return response()->json($path);
}
if ($request->hasFile('coverUpload')) {
$this->imageCover();
}
}
public function imageEntity()
{
$s3Path = config('app.path', public_path());
$image = Input::file('img');
Log::info('Retrieving Image', ['image' => $image]);
$filePath = 'public/logo/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$update_image = Entity::find($session);
$update_image->logo = $path;
$update_image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return response()->json($path);
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
public function imageCover()
{
$s3Path = config('app.path', public_path());
$image = Input::file('coverUpload');
Log::info('Retrieving Cover', ['image' => $image]);
$filePath = 'public/cover/' . time() . '.' . $image->getClientOriginalExtension();
$path = $s3Path . $filePath;
$this->S3Store($filePath, $image);
$session = session()->get('key');
try {
$image = new Images;
$image->path = $path;
$image->cover = true;
$image->entity_id = $session;
$image->save();
Log::info('Succesfully saved logo for', ['entity_id' => $session]);
return $path;
} catch (Exception $e) {
Log::error('Images:', ['message' =>$e->getMessage(), 'entity_id' => $session]);
}
}
Now the funny thing is response is 200, however it is empty ($path is defined) and ajax is triggering error: part of the code and not success. I have checked the log, and try has been successful:
[2017-10-16 11:22:01] local.INFO: Retrieving Image {"image":"[object]
(Illuminate\Http\UploadedFile: /tmp/phpHPchM4)"} [2017-10-16
11:22:01] local.INFO: Adding to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully added to S3 [2017-10-16 11:22:05] local.INFO:
Succesfully saved logo for {"entity_id":"324"}
Could anyone please help me solve this matter?
Update::
I have updated the controller so that the function returns $path, and main function return the response, however for some reason it is saying that $path is undefined, how to pass data from return to controller that is returned it?

how can i use post and files with ajax?

i'd like to know how can i use $_POST and $_FILES using ajax, i'm trying to upload an image and insert a value on my database with post.
i've tried but it doesn't work.
index.html
<div class="form-group">
<label> img </label>
<input type="file" name="img" id="img" />
<input type='hidden' id='value' value='<?=$_GET["p"]?>' />
</div>
ajax.js
$(document).ready(function() {
$('#upload').click(function() {
var value = $('#value').val();
var img = $('#img').val();
var string= 'value=' + value + '&img=' + img;
$.ajax({
type: "POST",
url: "ajax.php",
data: string,
dataType: "json",
success: function(data) {
var success = data['success'];
if (success == true) {
console.log('success');
} else {
console.log('error');
}
}
});
return false;
});
});
ajax.php
<?php
if(isset($_POST["value"]) && isset($_FILES["img"])) {
echo json_encode(array("success" => true));
} else {
echo json_encode(array("success" => false));
}
?>
The best approach is convert image to base64 first. This conversion is done in the change listener.
var files = [];
$("input[type=file]").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
};
reader.readAsDataURL(file);
});
});
$("form").submit(function(form) {
$.each(files, function(index, file) {
$.ajax({url: "/ajax-upload",
type: 'POST',
data: {filename: file.filename, data: file.data},
success: function(data, status, xhr) {}
});
});
files = [];
form.preventDefault();
});

codeigniter ajax loader error

I have a problem with my ajax loader in CI.
This is what I have tried so far:
<script type="application/javascript">
$(document).ready(function() {
$('#submit').click(function() {
var form_data = {
username : $('.username').val(),
password : $('.password').val(),
};
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'message'
});
loader.insertAfter($(this));
//.removeClass().addClass('loader').html('<img src="assets/img/ajax-loader.gif">').fadeIn(1000);
$.ajax({ //
url: "<?php echo site_url('login/ajax_check'); ?>",
type: 'POST',
async : false,
data: form_data,
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}
});
return false;
});
});
</script>
c_login.php controller
function ajax_check() {
//if($this->input->post('ajax') == '1') {
if($this->input->is_ajax_request()){
$this->form_validation->set_rules('username', 'username', 'trim|required|xss_clean');
$this->form_validation->set_rules('password', 'password', 'trim|required|xss_clean');
$this->form_validation->set_message('required', 'Please fill in the fields');
if($this->form_validation->run() == FALSE) {
echo validation_errors();
} else {
$this->load->model('m_access');
$user = $this->m_access->check_user($this->input->post('username'),$this->input->post('password'));
if($user) {
echo 'login successful';
//echo '<img src="assets/img/loader-bar.gif"> Hello!';
//$this->load->view('welcome');
} else {
echo 'unknown user'; //
//echo ' <img src="assets/img/icon_error.gif"> Username or password not valid';
}
}
}
}
UPDATE:
The problem is, it's just displaying the loader infinitely.
What I want to do is, if the user is valid, will show the loader.gif and then redirect to main page else will display the username or password incorrect. What is wrong with my code? Any ideas? Thanks.
It seems that you named your loader as "message" instead of creating a "message" new element and name your loader as "ajax_loader".
var loader = $('<img/>', {
'src':'assets/img/ajax-loader.gif',
'id':'ajax_loader'
});
var message = ...
...
'id':'message'
.
success: function(msg) {
$('#ajax_loader').remove();
$('#message').html(msg);
}

Categories