I have a directory tree structure. Each time I click a folder, jQuery.ajax fires and opens a jquery.php file.
This is my javascript code that triggers the jQuery.ajax:
jQuery('.directory').live('click',function() {
// Get dir name clicked
var dir = jQuery(this).find('span').html();
// Update dir list
getHTML('getDirList',dir, function(html){
jQuery('#fileDirList').html(html);
});
// Update file list
getHTML('getRowList',dir, function(html){
jQuery('#fileList').html(html);
});
});
function getHTML(instance, dir, callback) {
jQuery.ajax({
type: "POST",
url: "../wp-content/plugins/wp-filebrowser/jquery.php",
dataType: 'html',
data: {instance: instance, dir: dir},
success: function(html){
callback(html);
},
error: function(e) {
callback('[Error] ' + e);
}
});
}
In this file I have the following code in my jQuery.php file:
<?php
class jQueryFactory {
/**
* Get and output directory list
*/
public function getDirList() {
echo parent::getDirList();
}
/**
* Get images and list them in row format
*/
public function getRowList() {
echo parent::getRowList();
}
/**
* Create new directory
*/
function createDir() {
if(isset($_POST['new_dir'])) {
$result = parent::createDir($_POST['new_dir']);
echo $result;
}
}
/**
* Delete file
*/
function deleteFile() {
if(isset($_POST['file'])) {
$file = $_POST['file'];
parent::deleteImage($file);
}
}
}
// Does this work?
if(!isset($factory))
$factory = new jQueryFactory();
switch($_POST['instance']) {
case 'deleteImage' : $factory->deleteFile(); break;
case 'createDir' : $factory->createDir(); break;
case 'getDirList' : $factory->getDirList($dir); break;
case 'getRowList' : $factory->getRowList($dir); break;
}
?>
My question is: Do I have to fire this function each time I click?
Or can I fire once and then just call the various functions within the same user session?
Every Ajax request you make is going to result in a new request on server side.
It is normal in PHP to initialize classes and configuration variables on every request, so the way you show is fine and trying to persist the
jQueryFactoryobject across requests is not an idea worth pursuing. It shouldn’t be much of a performance problem either.If the process really needs speeding up, look into things like opcode caching.