I am wanting away to list all my files and folders in a JSON but I need to be able to call the files using jQuery
Basically what I have is the following
public function listproductimagedirectory($rootPath) {
$pathStack = array($rootPath);
$contentsRoot = array();
$contents = &$contentsRoot;
while ($path = array_pop($pathStack)) {
$contents[basename($path)] = array();
$contents = &$contents[basename($path)];
foreach (scandir($path) as $filename) {
if ('.' != substr($filename, 0, 1)) {
$newPath = $path.'/'.$filename;
if (is_dir($newPath)) {
array_push($pathStack, $newPath);
$contents[basename($newPath)] = array();
} else {
$contents[basename($filename)] = $newPath;
}
}
}
}
return $contentsRoot[basename($rootPath)];
}
which outputs
{"giftcard":{"31791_319x242_0.jpg":"..\/products\/giftcard\/31791_319x242_0.jpg","7520921_0_9999_lge_v1_m56577569834701600.jpg":"..\/products\/giftcard\/7520921_0_9999_lge_v1_m56577569834701600.jpg","AMF.jpg":"..\/products\/giftcard\/AMF.jpg","accor.jpg":"..\/products\/giftcard\/accor.jpg","accorhotel.png":"..\/products\/giftcard\/accorhotel.png","cellarmasters.png":"..\/products\/giftcard\/cellarmasters.png","dusk.png":"..\/products\/giftcard\/dusk.png","giftca_100ath_lrg.png":"..\/products\/giftcard\/giftca_100ath_lrg.png","giftca_100goo_lrg.png":"..\/products\/giftcard\/giftca_100goo_lrg.png","giftca_100sun_lrg.png":"..\/products\/giftcard\/giftca_100sun_lrg.png","giftca_20itu_lrg.png":"..\/products\/giftcard\/giftca_20itu_lrg.png","giftca_25abc_lrg.png":"..\/products\/giftcard\/giftca_25abc_lrg.png","giftca_25jay_lrg.png":"..\/products\/giftcard\/giftca_25jay_lrg.png","giftca_30bra_lrg.png":"..\/products\/giftcard\/giftca_30bra_lrg.png","giftca_30div_lrg.png":"..\/products\/giftcard\/giftca_30div_lrg.png","giftca_40ebg_lrg.png":"..\/products\/giftcard\/giftca_40ebg_lrg.png","giftca_50col_lrg.png":"..\/products\/giftcard\/giftca_50col_lrg.png","giftca_50cou_lrg.png":"..\/products\/giftcard\/giftca_50cou_lrg.png","giftca_50dot_lrg.png":"..\/products\/giftcard\/giftca_50dot_lrg.png","giftca_50dym_lrg.png":"..\/products\/giftcard\/giftca_50dym_lrg.png","giftca_50hoy_lrg.png":"..\/products\/giftcard\/giftca_50hoy_lrg.png","giftca_50itu_lrg.png":"..\/products\/giftcard\/giftca_50itu_lrg.png","giftca_50jac_lrg.png":"..\/products\/giftcard\/giftca_50jac_lrg.png","giftca_50jea_lrg.png":"..\/products\/giftcard\/giftca_50jea_lrg.png","giftca_50pet_lrg.png":"..\/products\/giftcard\/giftca_50pet_lrg.png","giftca_50por_lrg.png":"..\/products\/giftcard\/giftca_50por_lrg.png","giftca_50reb_lrg.png":"..\/products\/giftcard\/giftca_50reb_lrg.png","giftca_50san_lrg.png":"..\/products\/giftcard\/giftca_50san_lrg.png","isubscribe.jpg":"..\/products\/giftcard\/isubscribe.jpg","isubscribe.png":"..\/products\/giftcard\/isubscribe.png","peteralexander.png":"..\/products\/giftcard\/peteralexander.png","rydges hotel.png":"..\/products\/giftcard\/rydges hotel.png","smiggle.png":"..\/products\/giftcard\/smiggle.png","sportsgirl.png":"..\/products\/giftcard\/sportsgirl.png","sussan.png":"..\/products\/giftcard\/sussan.png","wiggles.png":"..\/products\/giftcard\/wiggles.png"}}
What I see and I could be wrong but there is nothing the allows me to tell the ID of the array for e.g I am use to calling a JSON by using the each function and using something like this
obj.title that would tell me that its the title of the json row.
put your objects in an array... so you would have..
var myobject = { giftcard: [ {filename: "image1.png", path: "path"}, {filename: "image2.png", path: "path""}, {filename: "image3.png", path: "path"} etc...]}
then you can:
$.each(myobject.giftcard, function(index, image) {
image.filename
image.path
});
Related
I am trying to post data to populate my HTML dropdowns using jQuery's $.post as shown below.
var county = $("#county");
var constituency = $("#constituency");
var ward = $("#ward");
populate_fields();
$('select[name="political"]').change(function(ev) {
ev.preventDefault();
populate_fields();
});
function populate_fields() {
// call the server side script, and on completion, update all dropdown lists with the received values.
county.html('').append($('<option>').text('Please choose a county'));
constituency.html('').append($('<option>').text('Please choose a constituency'));
ward.html('').append($('<option>').text('Please choose a ward'));
var data = {
// pass all the currently selected values to the server side script.
"county" : county.val(),
"constituency" : constituency.val(),
"ward" : ward.val()
}
$.post('php/dropdown.php', data, function (resp) {
console.log('function works');
all_values = resp;
$.each(all_values.county, function () {
$option = $("<option>").text(this).val(this);
if (all_values.current_county == this) {
$option.attr('selected', 'selected');
}
county.append($option);
});
$.each(all_values.constituency, function () {
$option = $("<option>").text(this).val(this);
if (all_values.current_constituency == this) {
$option.attr('selected', 'selected');
}
constituency.append($option);
});
$.each(all_values.ward, function () {
$option = $("<option>").text(this).val(this);
if (all_values.current_ward == this) {
$option.attr('selected', 'selected');
}
ward.append($option);
});
},'json');
}
the php file being referred to works perfectly, however the post does not receive data from this file and the function does not execute, I have traced the problem to the above snippet of code. Anyone have an Idea as to what could be the problem?
Here is my php Code as requested for more insight into the problem:
<?php
// read the CSV file in the $makes_models_years array
$makes_models_years = array();
//$uploads_folder = wp_upload_dir()['basedir'];
$file = fopen("./resources/polling_data.csv","r");
$firstline = true;
while (($line = fgetcsv($file)) !== FALSE) {
if ($firstline) {
$firstline = false;
continue;
}
$makes_models_years[$line[0]][$line[1]][] = $line[2];
}
fclose($file);
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'county' => array_keys($makes_models_years),
'constituency' => array(),
'ward' => array(),
'current_county' => false,
'current_constituency' => false
);
// print_r($return_array);
// collect the posted values from the submitted form
$make = key_exists('county', $_POST) ? $_POST['county'] : false;
$model = key_exists('constituency', $_POST) ? $_POST['constituency'] : false;
$year = key_exists('ward', $_POST) ? $_POST['ward'] : false;
// populate the $return_array with the necessary values
if ($make) {
$return_array['current_county'] = $make;
$return_array['constituency'] = array_keys($makes_models_years[$make]);
if ($model) {
$return_array['current_constituency'] = $model;
$return_array['ward'] = $makes_models_years[$make][$model];
if ($year) {
$return_array['current_ward'] = $year;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
print_r($return_array);
die();
?>
I realised that the issue was in the post not being able to read data returned by the php file. I solved it by placing the php file in the same directory as the javascript file, apparently they don't work well when in placed separate folders.
I'm trying to create a tree that shows on the front end.
The user gives a location which the backend reads and creates a tree from and sends this back.
This tree can look many different ways. How can i get it so that the front end reads this and created the right tree for it?
example:
Frontend sends the path: /usr/test/dir1/
Backend reads this with the following function:
function dirtree($dir)
{
$dh = scandir($dir);
$return = array();
foreach ($dh as $folder) {
if ($folder != '.' && $folder != '..') {
if (is_dir($dir . '/' . $folder)) {
$return[] = array($folder => $this->dirtree($dir . '/' . $folder));
} else {
$return[] = $folder;
}
}
}
return $return;
}
Backend returns something like:
{
"maindir": [
".DS_Store",
{
"dir1": []
},
{
"subdir1": [
".DS_Store",
{
"subdir2": [
{
"subdir3": []
},
{
"subdir4": []
}
]
},
}
How can I translate this to the front-end?
Or how can I add a type children to this?
I have a function inside a class, and I would like to get the result of this function, something like:
Returned dangerous functions are: dl, system
Here is my code
public final function filterFile(){
$disabled_functions = ini_get('disable_functions');
$disFunctionsNoSpace = str_replace(' ', '', $disabled_functions);
$disFunctions = explode(',', $disFunctionsNoSpace);
$this->disFunctions = $disFunctions;
// get file content of the uploaded file (renamed NOT the temporary)
$cFile = file_get_contents($this->fileDestination, FILE_USE_INCLUDE_PATH);
$found = array();
foreach($this->disFunctions as $kkeys => $vvals)
{
if(preg_match('#'.$vvals.'#i', $cFile))
{
array_push($found, $vvals);
}
} // end foreach
} // end filterFile
// calling the class
$up = new uploadFiles($filename);
$fileterringFile = $up->filterFile();
print_r($fileterringFile);
var_dump($fileterringFile);
EDIT: add 2 functions for errors:
// check if any uErrors
public final function checkErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
return true;
}
return false;
} // end checkErrors()
// print user errors
public final function printErrors(){
$countuErrors = count($this->uErrors);
if((IsSet($this->uErrors) && (is_array($this->uErrors) && ($countuErrors > 0))))
{
echo '<ul>';
foreach($this->uErrors as $uV)
{
echo '<li>';
echo $uV;
echo '</li>';
}
echo '</ul>';
}
} // end printErrors()
Thanks in advance
at the end of end filterFile, add:
return 'Returned dangerous functions are: '.implode(',',$found);
hi all when Using exif_imagetype() [function.exif-imagetype]: function for checking images if the user hits the submit button without uploading anything the exif function returns an error in the webpage itself. my question is how to get rid of this error. am pasting the error below
Warning: exif_imagetype() [function.exif-imagetype]: Filename cannot be empty in /mounted- storage/home98a/sub009/sc61374-HGPS/sitakalyanam.com/newsita/php4upload.class.php on line 88
<?php
/*
- PHP4 Image upload script
*/
class imageupload
{
//pblic variables
var $path = '';
var $errorStr = '';
var $imgurl = '';
//private variables
var $_errors = array();
var $_params = array();
var $_lang = array();
var $_maxsize = 1048576;
var $_im_status = false;
//public methods
function imageupload ()
{
//require 'photouploadconfig.php';
if($_GET['Choice']=="1")
{
require 'Photouploddir1.php';
}
elseif ($_GET['Choice']=="2")
{
require 'Photouploddir2.php';
}
elseif ($_GET['Choice']=="3")
{
require 'Photouploddir3.php';
}
elseif ($_GET['horoschoice']=="1")
{
require 'horosuploaddir.php';
}
elseif ($_GET['videoChoice']=="5")
{
require 'videouploaddir.php';
}
$this->_types = $types;
$this->_lang = $lang;
$this->_upload_dir = $upload_dir;
$this->_maxsize = $maxsize;
$this->path = $PHP_SELF;
if (is_array($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
}
function allowTypes ()
{
$str = '';
if (count($this->_types) > 0) {
$str = 'Allowed types: (';
$str .= implode(', ', $this->_types);
$str .= ')';
}
return $str;
}
// private methods
function _doSafeUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if (exif_imagetype($this->_params['tmp_name']) && in_a rray(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -4);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this->_up load_dir.$this->new_name);
$this->imgurl =$this->new_name;
//$this->imgurl = .$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _doUpload ()
{
preg_match('/\.([a-zA-Z]+?)$/', $this->_params['name'], $matches);
if(in_array(strtolower($matches[1]), $this->_types))
{
if ($this->_params['size'] > $this->_maxsize)
$this->_errors[] = $this->_lang['E_SIZE'];
else
$this->_im_status = true;
if ($this->_im_status == true)
{
$ext = substr($this->_params['name'], -3);
$this->new_name = md5(time()).$ext;
move_uploaded_file($this->_params['tmp_name'], $this- >_upload_dir.$this->new_name);
$this->imgurl = ''.$this->new_name;
//$this->imgurl = ''.$this->_upload_dir.''.$this->new_name;
//$this->imgurl = ''.$this->new_name;
//$this->imgurl = $this->_upload_dir.'/'.$this->new_name;
}
}
else
$this->_errors[] = $this->_lang['E_TYPE'];
}
function _errorMsg()
{
$this->errorStr = implode('<br />', $this->_errors);
}
}
?>
You are getting that message because you are never checking if the user uploaded a file or not, you're just assuming they are. When the user does not upload a file then $_FILES will be an empty array.
That means that $this->_params['tmp_name'] won't exist. You need to check if a file was uploaded, not just assume one was.
Just simply check the size of $_FILES.
if(count($_FILES) === 0){
echo "no file uploaded";
}
Change your code to this one and then try
if (isset($_FILES['__upload']))
{
$this->_params = $_FILES['__upload'];
if (function_exists('exif_imagetype'))
$this->_doSafeUpload();
else
$this->_doUpload();
if (count($this->_errors) > 0)
$this->_errorMsg();
}
This plugin reads image files on blueimproot/server/php/files on page load. I need to read records from database, and replace 'download' HTML structure with my custom structure. I want to show catalog products, which items are affected by uploading/removing images through this plugin.
I've done this so far:
I changed public function get() { ... } in blueimproot/server/php/upload.class.php to retrieve records from database. This function returns json object.
public function get() {
/* default code of Blueimp
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
*/
include_once('../../../../connection.php');
$id_cat = $_REQUEST['catid'];
$query = "SELECT id, name, price, img_path FROM products WHERE id_cat = $id_cat ORDER BY id";
$prods = mysql_query($query);
$prod_arr = array();
while($prod = mysql_fetch_assoc($prods)) {
$prod_arr[] = $prod;
}
header('Content-type: application/json');
echo json_encode($info);
}
I found that function is called from index.php in blueimproot/server/php:
switch ($_SERVER['REQUEST_METHOD']) {
...
case 'GET':
$upload_handler->get();
break;
...
}
I don't know where the returned json object is processed to show to UI. Have been 2 days and still can't track that function flow. Please help. Thanks.
Original Online Demo:
http://blueimp.github.com/jQuery-File-Upload/
Original Plugin Download:
https://github.com/blueimp/jQuery-File-Upload/downloads
My suggestion is to open up the Network Tab in Firebug and watch for any GET requests to server/php/index.php. If it happens after a specific event then you'll have a better idea of where you should look.
I did look through the source files and the only GET request I found was in main.js
$('#fileupload').each(function () {
var that = this;
$.getJSON(this.action, function (result) {
if (result && result.length) {
$(that).fileupload('option', 'done')
.call(that, null, {result: result});
}
});
});
}
public function get() {
/*
$file_name = isset($_REQUEST['file']) ?
basename(stripslashes($_REQUEST['file'])) : null;
if ($file_name) {
$info = $this->get_file_object($file_name);
} else {
$info = $this->get_file_objects();
}
header('Content-type: application/json');
echo json_encode($info);
*/
$id_cat = $_REQUEST['catid'];
$query = "SELECT id, name, price, img_path FROM products WHERE id_cat = $id_cat ORDER BY id";
$prods = mysql_query($query);
$prod_arr = array();
while($prod = mysql_fetch_assoc($prods)) {
//$prod_arr[] = $prod;
$file = new stdClass();
$file->name = "";// here image name goes i do not find image name in your select query
$file->size = filesize($prod["img_path"]);// should be complete path
$file->url = $prod["img_path"];// should be relative path (http://localhost/images/234.jpg)
$file->thumbnail_url = $prod["img_path"]; // thumbnail path
$this->delete_type = "DELETE";
$this->delete_url = ""; //here delete url you can delete image from database
array_push($prod_arr,$file);
}
header('Content-type: application/json');
echo json_encode($prod_arr);
}
Following this WIKI: https://github.com/blueimp/jQuery-File-Upload/wiki/Working-with-databases
I setup uploads to be inserted into a database, then i changed my GET function as follows:
public function get() {
$uploads = $this->query_db();
header('Content-type: application/json');
echo json_encode($uploads);
}
and my query_db function as follows:
public function query_db() {
$uploads_array = array();
$select_result = $this->query("SELECT * FROM `uploads` ORDER BY `file_name`") or die(mysql_error());
while($query_results = mysql_fetch_object($select_result))
{
$file = new stdClass();
$file->id = $query_results->id;
$file->name = $query_results->file_name;
$file->size = $query_results->file_size;
$file->type = $query_results->file_type;
$file->url = "http://files.domain.com/".$query_results->file_name;
$file->thumbnail_url = "http://thumbnails.domain.com/".$query_results->file_name;
$file->delete_url = "";
$file->delete_type = "DELETE";
array_push($uploads_array,$file);
}
return $uploads_array;
}