I installed BT Property component for my Joomla site and when I select multiple of images (more than 3 or 4) which I want to upload for my article, it nothing happens. The images won't upload. I try to change the code but I don't know what the problem is.
This is the code I want to change.
<?php
defined('_JEXEC') or die('Restricted access');
$document = JFactory::getDocument();
$path = $this->params->get('images_path', 'images/bt_property');
?>
<ul class="adminformlist" id="uploading">
<li><input type="file" name="attachment" id="attachment" multiple /><img id="spinner"
style="display: none; margin-left: 10px;"
src="<?php echo JURI::root(); ?>components/com_bt_property/assets/img/spinner.gif">
<div style="clear: both"></div>
<div id="btss-message"></div></li>
</ul>
<script type="text/javascript">
(function($){
var files = [];
$("#attachment").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);
if(files.length==1){
uploadFile(index);
$('#spinner').show();
$("#btss-message").show();
}
};
reader.readAsDataURL(file);
});
});
function uploadFile(index){
$.ajax({url: "index.php?option=com_bt_property&task=properties.upload",
type: 'POST',
data: {filename: files[index].filename, filedata: files[index].data},
success: function(response, status, xhr){
uploadHandler(response, status, xhr);
if(index == files.length-1){
$('#spinner').hide();
files = [];
$("#attachment").val('');
$("#btss-message").delay(1000).slideUp(function(){
$("#btss-message").html('');
});
}else{
index++;
uploadFile(index);
}
}
});
}
function uploadHandler(response, status, xhr) {
var data = jQuery.parseJSON(response);
if(data == null){
showMessage("<br /><span style=\"color: red;\">Loading Failed</span>");
}else{
var file = data.files;
if (!data.success) {
showMessage("<br /><span style=\"color: red;\"> " + data.message +"</span>");
}
else {
var html = '<li>';
html += '<input class="input-default" title="Make default" name="default_image" type="radio" value="'+file.filename+'" />';
html += '<img class="img-thumb" src="<?php echo JURI::root() . $path . '/tmp/' . ($this->params->get('thumbimgprocess', 1) == -1 ? 'original' : 'thumb') . '-'; ?>'+file.filename+'" />';
html += '<input type="hidden" name="image_id[]" value="0" />';
html += '<input type="hidden" name="image_filename[]" value="'+file.filename+'" /><br/>';
html +='Edit';
html +='<a href="javascript:void(0)" class="remove" onclick="removeImage(this)" >Remove</a>';
html += '</li>';
jQuery('#sortable').append(html);
jQuery('#sortable li:last-child ').find('a.edit').data('title', file.title);
reNewItem();
showMessage('<br />' + file.title + " uploaded successfully!");
}
}
}
function showMessage(msg){
$("#btss-message").append(msg);
}
})(jQuery);
</script>
Is there a way to fix the code? I would be very thankful for any answer.
Your file object is coming up as undefined, and thus you're not able to use file.filename.
Your problem is most likely with this line var file = data.files; - are you sure about data.files?
Related
how to get dynamic data from database in Wordpress ajax if their is already a query is running inside a function in Wordpress
<script type="text/javascript" >
var ajaxurl = "<?php echo admin_url('admin-ajax.php');?>";
jQuery(document).ready(function($) {
var data = {
'action': 'wa_action'
};
$.post(ajaxurl, data, function(result) {
var contactList = JSON.parse(result);
console.log(contactList);
var contents = '<ul id="whatsapps" class="list" >';
contactList.forEach(contact => {
contents += '<li class="child">';
contents += '<a href="https://wa.me/+91'+contact.contact_number+'" target="_blank">';
contents += '<img src="<?php echo PLUGIN_URL."/CustomPlugin/assets/images/whatsapp.png" ?>" class="img-fluid" target="_blank" alt="logo" />';
contents += '<span>'+contact.name + '(' + contact.designation +')' + '</span>';
contents += '</a>';
contents += '</li>';
});
contents += '<li class="parent"><a><img src="<?php echo PLUGIN_URL."/CustomPlugin/assets/images/whatsapp.png" ?>" class="img-fluid" target="_blank" alt="logo"></a></li>';
contents += '</ul>';
$('body').append(contents);
$("#whatsapps .parent").click(function () {
$("#whatsapps").toggleClass("show");
});
});
});
</script>
How to add CSS for positioning here
I had look to the similar question and its doesn't solve my problem
I want to create file multiple upload system with progressbar using php
and i have this error
Uncaught SyntaxError: Unexpected token < in JSON at position 0
at JSON.parse (<anonymous>)
at XMLHttpRequest.<anonymous>
my code is
<?php
error_reporting(0);
$state="white";
$count=0;
if(isset($_GET["state"])){
$state=$_GET["state"];
$count=$_GET["count"];
}
?>
<html >
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="keywords" content="كتابك القريب,أدهم شرقاوي,روايات, كتب pdf,تحميل كتب,كتب دراسية,pdf,books">
<meta name="google-site-verification" content="ieyWI-BKgki1_LGBMFqdFYkGyEeHlMSEAodDuxKcN7A" />
<link rel="stylesheet" href="controls.css">
<!--
-->
<style>
.bar
{
position: absolute;
height: 15px;
background-color: rgb(27, 26, 26);
box-shadow:inset 1px 1px 1px 1px #fff5;
width: 80%;
bottom: 45px;
border-radius:15px ;
}
.pbar
{
position: absolute;
height: 15px;
background-color:#941ab4;
width: 0;
border-radius:15px ;
}
</style>
<title>كتابك القريب</title>
<script src="jquery.js"></script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
var Vcount= <?php echo $count; ?>;
if (state=="succsses") {$(document).ready(function() { $(".succsses").css("display","block");}); }
</script>
<script>
var state= <?php echo '"' .$state.'"' ; ?>;
if (state=="error") { $(document).ready(function() { $(".error").css("display","block"); }); }
</script>
<script>
$(document).ready(function() {
$(".x").click(function() {
$(".succsses").css("display","none");
});
});
$(document).ready(function() {
$(".x").click(function() {
$(".error").css("display","none");
});
});
</script>
</head>
<body>
<div class="succsses" id="succsses" >
<p><?php if ($state=="succsses") { echo"تم تحميل ($count) ملفات بنجاح" ;}?></p>
<span class="x">x</span>
</div>
<div class="error" id="error" >
<p><?php if ($state=="error") { echo"فشل التحميل " ;}?></p>
<span class="x">x</span>
</div>
<div class="login-form">
<img src="https://yourclosebook.com/res/logos/ryhan.png" alt="" class="ava">
<form action="upload.php" method="post" enctype="multipart/form-data" id="frm">
<input type="email" name="email" id="" placeholder="email (اختياري)">
<input type="file" name="file[]" id="costum-file" accept="application/pdf,application/msword,.docx" multiple >
<input type="submit" value="تحميل" id="upload">
</form>
<div class="bar">
<span class="pbar" id="pb"></span> <span class="ptext " id="pt"></span>
</div>
<P> (*.pdf,*.docx,*.doc,*.ppt,*pptx)يمكنكم تحميل ملفات من الصيغ المدرجة جانبا</P>
<h3 id="friend"> <a href="https://www.yourclosebook.com" target="_blank" > كتابك القريب !</a> صديقك المقرب</h3>
</div>
<style>
</style>
<script src="upload.js"></script>
<script>
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
</body>
</html>
uploade.php
<?php
require_once("conn.php");
header("Content-Type:application/json");
$err="";
$UPLOADED=NULL;
$count=0;
$i=0;
$succeded=[];
$faild=[];
for ($i; $i <count($_FILES['file']['name']) ; $i++) {
$target_path="uploads/";
$file=$_FILES['file']['name'][$i];
$file_temp=$_FILES['file']['tmp_name'][$i];
$fileSize =$_FILES['file']['size'][$i];
$fileError =$_FILES['file']['error'][$i];
$fileType =$_FILES['file']['type'][$i];
$fileEXT =explode('.',$file);
$fileRealExt=strtolower(end($fileEXT));
$target_path= $target_path.$file;
$allowed =array('pdf','doc','docx');
if (!empty($file)) {
if (in_array($fileRealExt,$allowed)) {
if ($fileError===0) {
$helpTimes=1;
$email=$_POST['email'];
$email= $db->real_escape_string($email);
$file= $db->real_escape_string($file);
$UPLOADED=move_uploaded_file($file_temp,$target_path);
if ($UPLOADED) {
$insert = $db->query("INSERT INTO user_uploads(email,filepath,upload_time,help_times) VALUES('".$email."','".$file."',NOW(),'".$helpTimes."')");
$count=$i+1;
$succeded=array(
'name'=>$name,
'file'=>$file
);
}else{
$faild= array('name' => $name);
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
$err= "حدث خطأ غير متوقع";
echo header("Location:index.php?state=error&error=failedUpload");
}
}else{
echo header("Location:index.php?state=error&error=notAcceptedFileFormat");
}
}else{
$err=" يجب اختيار ملف واحد على الاقل";
echo header("Location:index.php?state=error&error=empty");
}
// --------------------
if (!empty($_POST['ajax'])) {
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
}
}
echo $err;
if ($count>0) {
//index.php
echo header("Location:index.php?state=succsses&count=$count");
if (!empty($_POST['email'])) {
$email=$_POST['email'];
$from = "MIME-Version: 1.0" . "\r\n";
$from .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$from .= 'From: YOUR CLOSE BOOK TEAM <contact#yourclosebook.com>' . "\r\n";
$s=" رسالة شكر";
$messagge="<H1>باسمنا نحن فريق موقع كتابك القريب نقد لكم فائق الشكر لاجل مساعدتنا بتقديم كتبكم الثمينة</H1>";
$mail= mail($email,$s,$messagge,$from);
if (!$mail) {
echo"email sending error";
}
else{
echo"check your email";
}
}
}else{
echo header("Location:index.php?state=error");
}
upload.js
var app=app ||{};
(function(o){
"use strict";
var ajax,getFormData,setProgress;
ajax =function (data)
{
var xhr= new XMLHttpRequest(),uploaded;
xhr.addEventListener('readystatechange',function()
{
//readyState===4 => done
if (this.readyState===4)
{
/*
status===200=> ok*/
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();
}
}
}
});
xhr.upload.addEventListener('progress',function(event)
{
var percent;//%
if (event.lengthComputable===true)
{
percent= Math.round((event.loaded/event.total)/100);
setProgress(percent);
}
});
xhr.open('post',o.options.processor);
xhr.send(data);
};
getFormData =function (source) {
var data = new FormData(),i;
for ( i = 0; i < source.length; i++) {
data.append('costum-file[]',source[i]);
}
data.append('ajax',true);
return data;
};
setProgress =function (value) {
if (o.options.porgressBar !== undefined) {
o.options.porgressBar.style.width=value?value+'%':0;
}
};
o.uploader=function (options) {
o.options=options;
if (o.options.files!==undefined) {
ajax(getFormData(o.options.files.files));
}
}
}(app));
There are some issues with your code:
In your main file you have an email element but in your upload.js file you are not adding it to your FormDara object. So in your uploade.php file you don't have access to it and $email=$_POST['email']; will throw an error
In your upload.js you are naming your file objects costum-file fun in your upload.php you are looking for file objects with the name of file. These two should have same name.
echo header("Location:index.php"); is incorrect and you should only use header("Location:index.php");
If you are calling upload.php file via ajax request then you can not do php redirect(header("Location:index.php");). What you should do is to return some json response and then pars it in your main file JavaScript and show relevant messages(Error or success)
So to sum them up what you need to change to fix the error you are getting is(I'm just highlighting the changes and not the whole code):
main(index.php?) file
You need to provide an id for the email element:
<input type="email" name="email" id="email" placeholder="email (اختياري)">
You need to add this email element to your JavaScript call
<script type="text/javascript">
document.getElementById('upload').addEventListener('click',function(e){
e.preventDefault();
var f = document.getElementById('costum-file');
var pb = document.getElementById('pb');
var pt = document.getElementById('pt');
var eml = document.getElementById('email');
app.uploader({
files:f,
porgressBar:pb,
porgressText:pt,
email:eml,
processor:'upload.php',
finished:function(data){
},
error:function(){
}
});
});
</script>
upload.js
You need to change the file element to file and also add the email element in the FormData object
getFormData =function (source) {
var data = new FormData(), i;
for ( i = 0; i < source.length; i++) {
data.append('file[]',source[i]);
}
data.append('email', o.options.email.value);
data.append('ajax', true);
return data;
};
And finally in your upload.php file change all the echo header("Location:index.php") instances with a json encoded string like what you have here:
echo json_encode(array(
'succeded'=> $succeded,
'faild'=>$faild
));
With proper response which then you can parse in your index.php file.
Please give it a try and see if it fixes your issue.
I'm trying to create a system of photos of a product, where the administrator if he wants to add remove or change the position of the photos he does everything by the form.
Form:
<form role="form" id="editProductForm" enctype="multipart/form-data">
<div id="SubPhotos" class="mt-3" style="overflow: auto; white-space: nowrap;">
<hr>
<div class="form-group mt-0 col-md-3">
<label for="uploadPhoto" class="btn btn-primary" role="button" style="cursor:pointer">Add Photo <i class="fas fa-plus"></i></label>
<input type="file" id="uploadPhoto" onchange="readURL(this);" style="display:none;">
</div>
<div class="d-flex">
<label><span id="badgeMainPicture" class='badge badge-primary ml-2'>Main Picture</span></label>
<label class="ml-auto"><span id="badgeTotalPhotos" class='badge badge-secondary'>Amount of Photos: <?php echo count($productImages) ?> de 10</span></label>
</div>
<div id="droppable" style="display: flex;">
<?php $index = 1;
for ($i = 0; $i < count($productImages); $i++) { ?>
<div id="photo<?php echo $index ?>" class="form-group col-lg-3 draggable">
<img id="preview-img" <?php echo isset($productImages[$i]) ? 'src="' . $site . $productImages[$i]['ImagePath'] . '"' : '' ?> height="300px" width="242px" />
<button id="removerPhoto<?php echo $index ?>" class="btn btn-danger btn-removerPhoto shadow-lg" type="button" onclick="removePhoto(<?php echo $index ?>)"><i class="fas fa-times"></i></button>
</div>
<?php
$index++;
} ?>
</div>
</div>
<hr>
<div class="d-flex">
<button type="submit" id="editProduct" class="ml-auto mr-auto btn btn-primary mt-5">Modify Product</button>
</div>
</form>
Contains remove button, draggable to change positions and add photos, everything works fine CLIENT-SIDE
After submit form:
$("#editProductForm").submit(function(e) {
e.preventDefault();
var index = 1;
$(".draggable").each(function() {
var image = $(this).find("#preview-img").attr("src");
var id = $(this).attr("id").substring(4);
if (image.indexOf("https://") > -1) {
$("#photo" + id).attr("id", "photo" + index);
} else {
$("#picture" + id).attr("name", "picture" + index);
}
index++;
});
var formData = new FormData(this);
var index = 1;
$(".draggable").each(function() {
var image = $(this).find("#preview-img").attr("src");
var id = $(this).attr("id").substring(4);
if (image.indexOf("https://") > -1) {
formData.append('picture' + index, image);
} else {
$("#picture" + id).attr("name", "picture" + index);
}
index++;
});
$.post({
url: '<?php echo $site ?>/admin/painel/modifyproduct.php',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
}
});
});
Now comes the question, my code has bug and I don't know how to solve SERVER-SIDE:
function createImage($id, $productCategory)
{
global $db;
$db->query("DELETE FROM pictures WHERE ProductID='$id'");
if (!file_exists("../../../pictures/produtos/$productCategory/MTA$id/")) {
mkdir("../../../pictures/produtos/$productCategory/MTA$id/", 0777, true);
}
$position = 0;
for ($i = 1; $i <= 10; $i++) {
if (isset($_FILES['picture' . $i])) {
$file = $_FILES['picture' . $i]['tmp_name'];
$nameFile = "picture" . $position;
$patchImage = "/pictures/produtos/$productCategory/MTA$id/$nameFile.png";
move_uploaded_file($file, "../../.." . $patchImage);
saveImageInDataBase($id, $patchImage, $position);
$position++;
} else if (isset($_POST['picture' . $i])) {
$file = $_POST['picture' . $i];
$nameFile = "picture" . $position;
$oldName = "../../../" . substr($file, strpos($file, 'pictures/'));
rename($oldName, "../../../pictures/produtos/$productCategory/MTA$id/$nameFile.png");
saveImageInDataBase($id, "/pictures/produtos/$productCategory/MTA$id/$nameFile.png", $position);
$position++;
}
}
}
Bug: There is a bug that when there is already a photo in the folder with the same name (with the position) and another photo being placed with that same position (move_uploaded_file) the old photo will be replaced.
Would there be an easier way to make this photo system work well?
Before doing the move_uploaded_file() you have to check whether the file exists. If so, you'll need to create a new filename. You'll have to do those steps until you find a non-existent file.
while ( TRUE ) { // Loop until we find a non-existent destination filename
$nameFile = "picture" . $position;
$patchImage = "/pictures/produtos/$productCategory/MTA$id/$nameFile.png";
if ( ! file_exists( $patchImage ) ) { // We're good
move_uploaded_file($file, "../../.." . $patchImage);
saveImageInDataBase($id, $patchImage, $position);
break; // Get out of the loop
}
$position++; // Try next position
}
I have created multiple image upload function with preview and remove option. But when i select files ,suppose 4 images and then it previews 4 images correctly. Now i remove 2 of them from preview and try to upload in database but it still uploading 4 images instead of 2 image.
$(document).ready(function() {
if (window.File && window.FileList && window.FileReader) {
$("#vpb-data-file").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$("<span class=\"pip\">" +
"<img class=\"imageThumb\" height=\"100\" width=\"100\" src=\"" + e.target.result + "\" title=\"" + file.name + "\"/>" +
"<br/><span class=\"remove\">Remove</span>" +
"</span>").insertAfter("#ml_image");
$(".remove").click(function() {
$(this).parent(".pip").remove();
});
// Old code here
/*$("<img></img>", {
class: "imageThumb",
src: e.target.result,
title: file.name + " | Click to remove"
}).insertAfter("#files").click(function(){
$(this).remove();
});*/
});
fileReader.readAsDataURL(f);
}
});
} else {
alert("Your browser doesn't support to File API")
}
});
<div class="card-body">
<div class="row" id="ml_image" style="margin-top:15px;">
<div class="col-md-3">
<label class="form-label">Upload Image<br>
<span style="font-size:12px;">(For multiple images press ctrl.)</span>
</label>
</div>
<div class="col-md-6">
<span onclick="product_image();" id="hide_span" class="btn btn-icon btn-primary file_upload_icon" style="margin-top:6px;"><i class="fas fa-cloud-upload-alt" style="font-size:31px;"></i><strong style="color:#000000;padding:10px;font-size:15px;">Choose File...</strong></span><input
style="display:none;" type="file" name="p_image[]" id="vpb-data-file" multiple />
</div>
</div>
<div class="row" id="vpb-display-preview"></div>
</div>
$p_image = count($_FILES['p_image']['name']);
print_r($p_image);
Here I am counting how many files I want to upload. I am getting 4 instead of 2.
Your remove function must remove file in e.target.files or in the p_image[] tab.
I wish to get the file size and show inside my disabled textbox.
I googled and there is very less info about this.
Following bellow is my code
In PHP:
<div class="inputWrapper">
<div class="usetitle">* <?php echo Yii::t('labels', 'gameapk'); ?> :
<div class="div_upload_file_container">
<div style="position:absolute; margin: 0; padding:0; height:27px">
<input style="display:none" id="btnUploadFile" name="btnUploadFile" type="file" />
</div>
<div class="div_upload_file_container_inner">
<div class='word'>
</div>
<div style='clear:both'></div>
</div>
</div>
<div style="height:50px"></div>
<div id="uploaded_file"></div>
</div>
<div class="error2"><div id="err_btnUploadFile"></div></div>
</div>
In JS FILE:
//file
$('#btnUploadFile').uploadify({
'swf': base_url + '/js/plugins/uploadify321/uploadify.swf',
'uploader': "index.php?r=apk/uploadfile",
'folder' : '/temp',
'queueID': 'uploaded_file',
'queueSizeLimit' : 1,
'progressData': 'speed',
'removeCompleted': false,
'width': $('.div_upload_file_container').width(),
'height': 28,
'fileTypeDesc': 'Apk Files (*.apk)',
'fileTypeExts': '*.apk;',
'fileSizeLimit': '100GB',
'uploadLimit' : 1,
'itemTemplate': uploadedFileItem(),
'buttonText' : UPLOAD_FILE,
'onSelect': function (file) {
},
'onUploadStart': function (file) {
},
'onUploadSuccess': function (file, data, response) {
console.log (data);
$('#' + file.id).html(file.name);
var obj = JSON.parse(data);
statusCode = obj.statusCode;
if (statusCode == '200'){
console.log (data);
var today = obj.today;
var tmp_folder_with_date = obj.tmp_folder_with_date;
var filesize = obj.filesize;
var hashfilename_filename = obj.hashfilename_filename;
var full_path = obj.full_path;
file_cnt ++;
var html = '';
html = '<div>';
html += '<div style="float:left">';
html += file_cnt + '.';
html += '</div>';
html += '<div style="float:left; margin: 0 0 0 10px">';
html += file.name;
html += '</div>';
html += '<div style="clear:both"></div>';
html += '</div>';
$('#' + file.id).html(html);
}
var params = {
fileid: file.id,
fileName: obj.fileName,
fullSavePath_original: obj.fullSavePath_original,
fullSavePath_resize: obj.fullSavePath_resize,
fullSavePath_tobesave: obj.fullSavePath_tobesave,
fullSavePath_tobesaveURL: obj.fullSavePath_tobesaveURL,
filesize: obj.fileSize,
fullPath_TempFolder: obj.fullPath_TempFolder,
orientation: obj.orientation,
tobesave_file_width: obj.tobesave_file_width,
tobesave_file_height: obj.tobesave_file_height,
todayTempFolder: obj.todayTempFolder
};
DisplayNewUploadedPhotos(params);
},
'onUploadComplete': function (file) {
},
'onCancel': function (event,ID,fileObj,data) {
},
'onDialogClose': function (queueData) {
},
'onInit': function (instance) {
},
'onQueueComplete': function (queueData) {
},
'onClearQueue': function (queueItemCount) {
}
});
function uploadedFileItem() {
var html = '';
html = '<div id="${fileID}" class="fileUploadedItem">';
html += '<div style="margin:10px 0 0 0"></div>';
html += '<div class="uploadify-progress-bar"></div>';
html += '<div style="margin:10px 0 0 0">';
html += '<center>Cancel</center>';
html += '</div>';
html += '</div>';
return html;
}
obj.filesize is the file size ... Am I correct ? If I was correct , what should I do to get obj.filesize from JS to my textbox ?
I have an idea to do that suddenly:
$("#appsize").attr('value', obj.filesize);
HAHA THANKS =D