Create dropdown with directory contents - javascript

I have the below script that loads a json editor. The path to the json file that should be loaded is stored in a php var called $filePath. This works well however instead of loading a pre-determined json file I would like to have a dropdown list of all files in a specified directory ($dirPath) that the user can choose from. Any help would be greatly appreciated.
<?php global $filePath, $dirPath; ?>
<script>
// create the editor
var container = document.getElementById('jsoneditor');
var options = {
mode: 'view',
modes: ['code', 'text', 'view'], // allowed modes
onError: function (err) {
alert(err.toString());
},
onModeChange: function (newMode, oldMode) {
console.log('Mode switched from', oldMode, 'to', newMode);
}
};
var editor = new JSONEditor(container, options);
// set json
document.getElementById('setJSON').onclick = function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': "<?php echo $filePath; ?>",
'dataType': "json",
'success':
function (data) { json = data; }
});
editor.set(json);
};
</script>

Related

summernote js upload image

I'm using summernote version 0.8.1 (current).
It's working. But 1 thing I struggle with. Inserting an image, rather than putting base64 dataURL, I want to upload the image to the server and insert the image URL in the database. This is my code:
<script>
$(document).ready(function() {
$('#summernote').summernote({
lang: 'fr-FR',
height: 300,
toolbar : [
['style',['bold','italic','underline','clear']],
['font',['fontsize']],
['color',['color']],
['para',['ul','ol','paragraph']],
['link',['link']],
['picture',['picture']]
],
onImageUpload: function(files, editor, welEditable) {
for (var i = files.lenght - 1; i >= 0; i--) {
sendFile(files[i], this);
}
}
});
function sendFile(file, el) {
var form_data = new FormData();
form_data.append('file',file);
$.ajax ({
data: form_data,
type: "POST",
url: "../up.php",
cache: false,
contentType: false,
processData: false,
success: function(url) {
$(el).summernote('editor.insertImage',url);
}
})
}
});
</script>
I have tested the script up.php and what that does is changing the file name and returning the image's url in the form "../photos/mypicture.jpg".
The problem with the above code is that the ..up.php doesn't even seem to be called. I ran this in Firefox development tools and got no errors or warnings.
I got it working. Here's my code. Using summernote 0.8.1, i.e. current version.
<script>
$(document).ready(function() {
var IMAGE_PATH = 'http://www.path/to/document_root/';
// the exact folder in the document_root
// will be provided by php script below
$('#summernote').summernote({
lang: 'fr-FR', // <= nobody is perfect :)
height: 300,
toolbar : [
['style',['bold','italic','underline','clear']],
['font',['fontsize']],
['color',['color']],
['para',['ul','ol','paragraph']],
['link',['link']],
['picture',['picture']]
],
callbacks : {
onImageUpload: function(image) {
uploadImage(image[0]);
}
}
});
function uploadImage(image) {
var data = new FormData();
data.append("image",image);
$.ajax ({
data: data,
type: "POST",
url: "../up.php",// this file uploads the picture and
// returns a chain containing the path
cache: false,
contentType: false,
processData: false,
success: function(url) {
var image = IMAGE_PATH + url;
$('#summernote').summernote("insertImage", image);
},
error: function(data) {
console.log(data);
}
});
}
});
</script>
Here my up.php :
<?php
require('admchir/nettoie.php');
// nettoie.php removes the French special chars and spaces
$image = nettoie($_FILES['image']['name']);
$uploaddir = 'photos/';
// that's the directory in the document_root where I put pics
$uploadfile = $uploaddir . basename($image);
if( move_uploaded_file($_FILES['image']['tmp_name'],$uploadfile)) {
echo$uploadfile;
} else {
echo "Lo kol kakh tov..."; // <= nobody is perfect :)
}
?>
From looking for this on the internet, I got the impression that summernote changed a lot between the various versions, but didn't find a full working example of the current version. Hope this helps someone.
This is how I integrated it with Codeigniter 3, Summernote 0.8.1:
I am posting my working solution here so that anyone else can get some help or idea on how to implement summernote with image upload in CI 3 with CSRF.
the javascript code:
<!-- include libraries(jQuery, bootstrap) -->
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.js"></script>
<!-- include summernote css/js-->
<link href="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.css" rel="stylesheet">
<script src="http://cdnjs.cloudflare.com/ajax/libs/summernote/0.8.1/summernote.js"></script>
<script>
$(document).ready(function () {
$('#content').summernote({
height: 400,
callbacks: {
onImageUpload: function (image) {
sendFile(image[0]);
}
}
});
function sendFile(image) {
var data = new FormData();
data.append("image", image);
//if you are using CI 3 CSRF
data.append("<?= $this->security->get_csrf_token_name() ?>", "<?= $this->security->get_csrf_hash() ?>");
$.ajax({
data: data,
type: "POST",
url: "<?= site_url('summernote-image-upload') ?>",
cache: false,
contentType: false,
processData: false,
success: function (url) {
var image = url;
$('#content').summernote("insertImage", image);
},
error: function (data) {
console.log(data);
}
});
}
});
</script>
the codeigniter part:
//add this line in your routes.php
$route['summernote-image-upload'] = 'welcome/summernote-image-upload';
//now add this method in your Welcome.php Controller:
function summernote_image_upload() {
if ($_FILES['image']['name']) {
if (!$_FILES['image']['error']) {
$ext = explode('.', $_FILES['image']['name']);
$filename = underscore($ext[0]) . '.' . $ext[1];
$destination = './public/images/summernote/' . $filename; //change path of the folder...
$location = $_FILES["image"]["tmp_name"];
move_uploaded_file($location, $destination);
echo base_url() . 'public/images/summernote/' . $filename;
} else {
echo $message = 'The following error occured: ' . $_FILES['image']['error'];
}
}
}
the HTML part:
<textarea name="content" id="content"><?= html_entity_decode(set_value('content')) ?></textarea>
<?= form_error('content') ?>
note if you face issue with CSRF (for any reason), then you can exclude the summernote ajax upload in your config.php file:
$config['csrf_exclude_uris'] = array('summernote-image-upload');

Unable to validate the JS variable in PHP file

i have three files index.html , getData.php and data.json
index.html ->
<script type="text/javascript">
function load() {
var jsonData = $.ajax({
url: "getData.php",
type: "GET",
data: {variable: "loadavg"},
dataType:"json",
async: false
}).responseText;
// Create our data table out of JSON data loaded from server.
var data = new google.visualization.DataTable(jsonData);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, {width: 800, height: 400});
}
</script>
<ul class="list">
<p>Load average <input id="loadAvg" type="button" value="Enter" onclick="load();" /> </p>
</ul>
getData.php ->
<?php
// It reads a json formatted text file and outputs it.
if(isset($_GET["variable"]) == "loadavg"){
$string = file_get_contents("data.json");
echo $string;
// if this works you should see in console 'graph on cosole'
}
?>
data.json ->
{
"cols": [
{"id":"","label":"HostName","type":"string"},
{"id":"","label":"CPU","type":"number"},
{"id":"","label":"Free Avg memory","type":"number"}
],
"rows": [
{"c":[{"v":"lp10b2vapp01,w10"},{"v":21}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":15}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":73}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":60}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":48}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":40}]},
{"c":[{"v":"lp10b2vapp01,w10"},{"v":36}]}
]
}
when i click on button i was unable to see the output (Graph) ,Kindly look help me
Thanks in advance
Don't use async: false. It's terribly bad practice as it locks the UI thread making the browser look to the user like it has crashed until the request completes. Instead use the async callbacks which $.ajax provides you to update the UI of the page once the request has finished. Try this:
function load() {
$.ajax({
url: "getData.php",
type: "GET",
data: {
variable: "loadavg"
},
dataType: "json",
success: function(jsonData) {
var data = new google.visualization.DataTable(jsonData);
var chart = new google.visualization.ColumnChart($('#chart_div')[0]);
chart.draw(data, {
width: 800,
height: 400
});
}
});
}
Also note that you need to get the value of the parameter in the PHP code as well as checking it exists:
if (isset($_GET["variable"]) && $_GET["variable"] == "loadavg")
{
// code here...
}

Send custom data with dropzone.js on each File Upload

I am using dropzone in my Code Igniter Project.
With every drag of a file, dropzone creates an ajax request and my files is getting stored on the server too. But now, my requirement is that I want to send additional data (DYNAMIC) alongside the file.
With the use of params, Only static datas can be sent, but the data I want to send will be changing everytime.
This is how my code looks:
<script>
Dropzone.autoDiscover = false;
Dropzone.options.attachment = {
init: function(){
this.on('removedfile',function(file){
// console.log('akjsdhaksj');
var fileName = file.name;
$.ajax({
type: 'POST',
url: "<?php echo BASE_URL.'index.php/admin/mail_actions/deleteFile' ?>",
data: "id="+fileName,
dataType: 'html'
});
});
},
// params: {
// customerFolder: $('#toValue').substr(0, toValue.indexOf('#')),
// },
dictDefaultMessage:"Click / Drop here to upload files",
addRemoveLinks: true,
dictRemoveFile:"Remove",
maxFiles:3,
maxFilesize:8,
}
$(function(){
var uploadFilePath = "<?php echo BASE_URL.'index.php/admin/mail_actions/uploadFile' ?>";
var myDropzone = new Dropzone("div#attachment", { url: uploadFilePath});
});
</script>
Anyway I can achieve it?
I got it.
This is what I had to use
myDropzone.on('sending', function(file, xhr, formData){
formData.append('userName', 'bob');
});
Abhinav has the right and working answer I only want to give a second option to use it in the options object (for example if you have multiple Dropzone sections on one page.)
myDropzone.options.dropzoneDivID = {
sending: function(file, xhr, formData){
formData.append('userName', 'Bob');
}
};
In case you have a nested payload object - e.g. to add a name to your file and your api only accepts something like this
{
someParameter: {
image: <my-upload-file>,
name: 'Bob'
}
}
your dropzone setup would look like this
var myDropzone = new Dropzone("div#attachment", {
url: uploadFilePath,
paramName: 'someParameter[image]'
});
myDropzone.on('sending', function(file, xhr, formData){
formData.append('someParameter[image]', file);
formData.append('someParameter[userName]', 'bob');
});
I only added this as there was no example for nested parameters documented since now.
i was using JQuery and this is how worked for me :
$("#dZUpload").dropzone({
url: "ajax/upload_img_ben.php",
success: function (file, response) {
var imgName = response;
file.previewElement.classList.add("dz-success");
console.log("Successfully uploaded :" + imgName);
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
sending: function(file, xhr, formData){
formData.append('id', '5');
}
});

pass a php variable from one page to another page with ajax code

I dunno whether my heading is correct or not ??
While loading the shop.php page i have a variable named $curr set with values from GET like "GBP".
$curr = $_GET['cur'];
<script type="text/javascript" src="js/cart.js"></script>
While loading the page the cart.js code calls another page like as follows:
GET http://myshop.com/cart/config-loader.php?ajax=true
The javascript code which loads the config-loader page is as follows:
var config = (function() {
var config = null;
$.ajax({
url: path + '/config-loader.php',
data: {
"ajax": "true"
},
dataType: 'json',
async: false,
success: function(response) {
config = response;
},
error: function() {
alert('Ajax error: Edit the path in cart.js to fix.');
}
});
return config;
}());
I need to get the url passed as:
http://myshop.com/cart/config-loader.php?ajax=true&curr=GBP
so that i can get the $_GET['curr'] value in config-loader.php page.
My aim is to change the value USD to any other value like GBP in config-loader.phpge:
if (!$config['currencyCode']) $config['currencyCode'] = 'USD';
How can i do this in above code ?? Help requested from experts.
Use:
data: {
"ajax": "true",
"curr": <?php echo json_encode($curr) ?>
},

Dropzone.js- How to delete files from server?

I am using dropzone.js.
When I try to delete files only the thumbnails get deleted but not the files from server.
I tried some ways but it just gives me the name of the image which was on client side and not the name on server side(both names are different, storing names in encrypted form).
Any help would be much appreciated..
Another way,
Get response from your server in JSON format or a plain string (then use only response instead of response.path),
dropzone.on("success", function(file, response) {
$(file.previewTemplate).append('<span class="server_file">'+response.path+'</span>');
});
Here, the server can return a json like this,
{
status: 200,
path: "/home/user/anything.txt"
}
So we are storing this path into a span that we can access when we are going to delete it.
dropzone.on("removedfile", function(file) {
var server_file = $(file.previewTemplate).children('.server_file').text();
alert(server_file);
// Do a post request and pass this path and use server-side language to delete the file
$.post("delete.php", { file_to_be_deleted: server_file } );
});
After the process, the preview template will be deleted by Dropzone along with file path stored in a span.
The way I handle this, is after each file is uploaded and stored on the server, I echo back the name I give the file on my server, and store it in a JS object, something like this:
PHP:
move_uploaded_file($_FILES['file']['tmp_name'], $newFileName);
echo $newFileName;
JS:
dropZone.on("success", function(file, serverFileName) {
fileList[serverFileName] = {"serverFileName" : serverFileName, "fileName" : file.name };
});
With this, you can then write a delete script in PHP that takes in the "serverFileName" and does the actual deletion, such as:
JS:
$.ajax({
url: "upload/delete_temp_files.php",
type: "POST",
data: { "fileList" : JSON.stringify(fileList) }
});
PHP:
$fileList = json_decode($_POST['fileList']);
for($i = 0; $i < sizeof($fileList); $i++)
{
unlink(basename($fileList[$i]));
}
Most simple way
JS file,this script will run when you click delete button
this.on("removedfile", function(file) {
alert(file.name);
$.ajax({
url: "uploads/delete.php",
type: "POST",
data: { 'name': file.name}
});
});
php file "delete.php"
<?php
$t= $_POST['name'];
echo $t;
unlink($t);
?>
The file will be deleteed when you click the "Remove" button :
Put this on your JS file or your HTML file (or your PHP view/action file):
<script type="text/javascript">
Dropzone.options.myAwesomeDropzone = {
// Change following configuration below as you need there bro
autoProcessQueue: true,
uploadMultiple: true,
parallelUploads: 2,
maxFiles: 10,
maxFilesize: 5,
addRemoveLinks: true,
dictRemoveFile: "Remove",
dictDefaultMessage: "<h3 class='sbold'>Drop files here or click to upload document(s)<h3>",
acceptedFiles: ".xls,.xlsx,.doc,.docx",
//another of your configurations..and so on...and so on...
init: function() {
this.on("removedfile", function(file) {
alert("Delete this file?");
$.ajax({
url: '/delete.php?filetodelete='+file.name,
type: "POST",
data: { 'filetodelete': file.name}
});
});
}}
</script>
..and Put this code in your PHP file :
<?php
$toDelete= $_POST['filetodelete'];
unlink("{$_SERVER['DOCUMENT_ROOT']}/*this-is-the-folder-which-you-put-the-file-uploaded*/{$toDelete}");
die;
?>
Hope this helps you bro :)
I've made it easier, just added new property serverFileName to the file object:
success: function(file, response) {
file.serverFileName = response.file_name;
},
removedfile: function (file, data) {
$.ajax({
type:'POST',
url:'/deleteFile',
data : {"file_name" : file.serverFileName},
success : function (data) {
}
});
}
success: function(file, serverFileName)
{
fileList['serverFileName'] = {"serverFileName" : serverFileName, "fileName" : file.name };
alert(file.name);
alert(serverFileName);
},
removedfile: function(file, serverFileName)
{
fileList['serverFileName'] = {"serverFileName" : serverFileName, "fileName" : file.name };
alert(file.name);
alert(serverFileName);
}
When you save the image in upload from there you have to return new file name :
echo json_encode(array("Filename" => "New File Name"));
And in dropzone.js file :
success: function(file,response) {
obj = JSON.parse(response);
file.previewElement.id = obj.Filename;
if (file.previewElement) {
return file.previewElement.classList.add("dz-success");
}
},
And when the dropzone is initialize..
init: function() {
this.on("removedfile", function(file) {
var name = file.previewElement.id;
$.ajax({
url: "post URL",
type: "POST",
data: { 'name': name}
});
});
return noop;
},
Now you will receive new image file and you can delete it from server
You can add id number of uploaded file on the mockFile and use that id to delete from server.
Dropzone.options.frmFilesDropzone = {
init: function() {
var _this = this;
this.on("removedfile", function(file) {
console.log(file.id); // use file.id to delete file on the server
});
$.ajax({
type: "GET",
url: "/server/images",
success: function(response) {
if(response.status=="ok"){
$.each(response.data, function(key,value) {
var mockFile = {id:value.id,name: value.name, size: value.filesize};
_this.options.addedfile.call(_this, mockFile);
_this.options.thumbnail.call(_this, mockFile, "/media/images/"+value.name);
_this.options.complete.call(_this, mockFile);
_this.options.success.call(_this, mockFile);
});
}
}
});
Server Json return for getting all images already uploaded /server/images:
{
"data":[
{"id":52,"name":"image_1.jpg","filesize":1234},
{"id":53,"name":"image_2.jpg","filesize":1234},
]}
In my case server sends back some ajax response with deleteUrl for every specific image.
I just insert this url as 'data-dz-remove' attribute, set in previewTemplate already.
As I use jquery it looks so:
this.on("success", function (file, response) {
$(file.previewTemplate).find('a.dz-remove').attr('data-dz-remove', response.deleteUrl);
});
Later this attr used to send ajax post with this url to delete file on server by removedfile event as mentioned above.
This simple solution will work for single files upload, no need for DOM manipulation.
PHP Upload Script
[...]
echo $filepath; // ie: 'medias/articles/m/y/a/my_article/my-image.png'
JS Dropzones
this.on("success", function(file, response) {
file.path = response; // We create a new 'path' index
});
this.on("removedfile", function(file) {
removeFile(file.path)
});
JS outside of Dropzone
var removeFile = function(path){
//SEND PATH IN AJAX TO PHP DELETE SCRIPT
$.ajax({
url: "uploads/delete.php",
type: "POST",
data: { 'path': path}
});
}

Categories