Hello, I am trying to create a class with a method in which I can load js and css dynamically.
The problem is: since some PHP documents are in the root folder and others are in a sub-folder, the path of the js file changes depending on where you are calling. Some I must add "../" and in other cases I should not add it.
since the list of JS files is extensive and repeated in almost all the pages of the system
I have created an array with all the names of the .js documents that I should call
$ListaJs =array(
'modernizr.min.js',
'retina.js',
'tmpl.min.js',
'load-image.min.js',
'canvas-to-blob.min.js',
'jquery.iframe-transport.min.js',
'jquery.fileupload.min.js',
'jquery.fileupload-fp.min.js',
'jquery.fileupload-ui.min.js',
'jquery.fileupload-init.js',
'jquery.timeago.js',
'jquery.slimscroll.min.js',
'jquery.autosize-min.js',
'charCount.js',
);
This is how my folder is distributed ( all the js are in the asset / javascript folder )
--assets
----img
----javascript
----css
--clases
----cargar.php
--sistema
----login.php
--index.php
in the document carga.php I have the following code
class cargar {
private $direccion ;
function __construct(){
$this->direccion = dirname(__DIR__);
}
public function loadJS(){
$ListaJs =array(
'modernizr.min.js',
'retina.js',
'tmpl.min.js',
'load-image.min.js',
'canvas-to-blob.min.js',
'jquery.iframe-transport.min.js',
'jquery.fileupload.min.js',
'jquery.fileupload-fp.min.js',
'jquery.fileupload-ui.min.js',
'jquery.fileupload-init.js',
'jquery.timeago.js',
'jquery.slimscroll.min.js',
'jquery.autosize-min.js',
'charCount.js',
);
$script = "";
foreach ($ListaJs as $key => $value) {
//$direccion = $_SERVER['DOCUMENT_ROOT'];
$script .= "<script src='". $this->direccion ."/assets/javascripts/" .$value ." type='text/javascript'></script> </br>";
}
return $script;
}
}
and I call the function either in index.php or in login.php to load the JS in the page ( I do not know if it's ok to use Echo ""; )
// pido que se importe la clase cargar
require_once('clases/cargar.php');
// instancio la clase
$test = new cargar;
// llamo la funcion
$datos = $test->loadJS();
//imprimo los js
echo $datos;
shows me the following error
How could I solve the error I have tried by initializing the variable $direccion
from the constructor with $_SERVER['DOCUMENT_ROOT']