How do I make relative file pathing work with include()? - javascript

I'm working on a website, and the relevant portion of my file structure is:
site
classes
class1
js
Now, the js contains scripts that use other scripts within the same folder. The only way I can get the scripts to load properly on the php pages is to either copy the whole js folder into the relevant subfolder, or move the page to the site folder. Neither of these options is good.
I know that the issue is with the file pathing, so how do I get the includes in the js scripts to path relative to their location, and not the location of the php page?
An example of this:
I have a page in class1 called class1home.php.
It calls a js script called script.js.
script.js contains a function with include(script2.js), which is in the js folder.
Because of the pathing, the include is looking for site/classes/class1/script2.js.
I want it to go to site/js/script2.js.
Because there are multiple folders and scripts using script2.js, I can't just change the filepath within the include to be relative to that specific page.
Within script.js:
/**
* #function Include
* #description Includes an external scripts to the page
* #param {string} scriptUrl
*/
function include(scriptUrl) {
document.write('<script src="' + scriptUrl + '"></script>');
}
One place it is used (within script.js):
/**
* #module ToTop
* #description Enables ToTop Plugin
*/
(function ($) {
var o = $('html');
if (o.hasClass('desktop')) {
include('js/jquery.ui.totop.min.js');
$(document).ready(function () {
$().UItoTop({
easingType: 'easeOutQuart',
containerClass: 'ui-to-top fa fa-angle-up'
});
});
}
})($);

I normally solve this type of problem by having the page identify where it is with a call to Server. It looks like this:
$callingPageURL =$_SERVER['SCRIPT_FILENAME'];
Then, I parse that string to determine the file and the folder, by using the explode function. It looks like this:
$callingPageURLHolder = explode("/", $callingPageURL);
This loads up an array of values into callingPageURLHolder. From there, I use common data structure methods, like array pops, to get to the part of the URL that I think will be relevant to the program. It looks like this:
$callingPageFile = array_pop($callingPageURLHolder);
$callingPageFolder = array_pop($callingPageURLHolder);
Once you can parse out the array that comes back from Server, you could simply load up variables you need to concatenate into a URL that you will call in your include.
This same type of technique can be used to make small changes in a template page based on where it was included from, by adding in some flow control that tests these kinds of extracted values.
For example,
switch ($callingPageFile){
case "index.php":
// some response
break;
}
Using logic like that, I might build chains of cases in which I respond to anticipated URL parts. I use this type of code for when I might want to slightly customize a PHP page. Using these techniques, and some planning, you might be able to respond to the idea that you intend to transplant your code to a variety of places.

Related

JS .load() not working inside a triple parameter url rewrite?

im building a backoffice which has already this function working on single parameter url like example.com/backoffice/page
but on this page is not working the link is like this : example.com/backoffice/editassembly/2
This is the JS code of the page :
// When the document is ready set up our sortable with it's inherant function(s)
$("#todos").sortable({
handle: "#handle",
update: function() {
var order = $('#todos').sortable('serialize');
$("#info").load("../scripts/ficheiroassembleia.php?" + order);
}
});
This code is completly correct and working on other pages, the thing is that the .load is not loading my script like it could not reach it.
The current module for the page im using is inside the folder "www/backoffice/modules/editassembly/" and the script is inside "www/scripts/"
I already found out the problem, it was due to fact that the include for header that contained all important js files was not loading corretly, path issue i had to make a call on the file itself since it was the only module using a tripple parameter.

Accessing file with JS when files are a folder deeper than domain

We have a MVC site which uses subdomains. Not in the traditional sub.domain.com but instead we are using domain.com/sub. The source files all exist in the sub folders of each sub domain because each might have some slightly different things. This causes the Dev team to have to place JS directly into the razor pages so the razor code was able to update URLs like below.
var temp = $('div').load('#Url.Content("~/Images/Excel.png")');
Unfortunately using a code like below in a separate JS file tries loading from domain.com and not domain.com/sub
var temp = $('div').load('/Content/Templates/warning.html');
Theses add on to the domains and can change with clients. Is there a way to get the domain plus sub when the files are loaded like that in the JS without needing to place the code into the razor? I'd prefer a separation of concerns because we are loading scripts sometimes which aren't even used because of it.
what I always do when in similar situations is that I create a function in the main.js or whatever name your using for your shared js file, modify the URL in the function and use the function as the initiator:
in the main.js:
var loadFile = function(selector,path){
$(selector).load('/sub'+path);
}
and then whenever and wherever you wanna load a file:
var temp = loadFile('div','/Content/Templates/warning.html');
UPDATE
you can upgrade your loadFile function to let it know if it has to load from the root of the website if needed:
var loadFile = function(selector,path,loadFromRoot){
var root=(loadFromRoot) ? '' : '/sub';
$(selector).load(root+path);
}

How to reference documents in my website to be independent of the website location and usage location

I'm relatively new to client side development. I'm creating an angularJS directive which references a static html, in [root]/Static/template.html.
I guess the problem is not unique to angularJS.
Now I need this address to be root relative, so that it can be loaded regardless of where I use the directive. The problem is that I don't know where my site will be uploaded, so it might be put in www.mysite.com/ or might be www.mysite.com/system/
I also can't use relative path, as it will be sensitive to where I use the directive, so for instance if I use Static/template.html, it will be found by documents in the website root, but not in the inner folders.
What is the correct way to reference documents to be robust?
If your static folder is relative the place where your application is deployed, e.g.:
www.example.com/index.html
www.example.com/Static
www.example.com/root/index.html
www.example.com/root/Static
www.example.com/root/foobar-app/index.html
www.example.com/root/foobar-app/Static
Then you need to extract the base url and store it somewhere. window.location API could be used to do that.
E.g.:
<!-- index.html -->
<!-- should probably be placed into external script file -->
<script>
function extractPath(url) {
return url.match(/.*\//) // find all chars until the slash
}
var baseurl = window.location.origin + extractPath(window.location.pathname);
window.baseurl = baseurl; // store in global scope
</script>
This snippet shows the general idea. Now elsewhere in your code you can read the base url path to access static resources. E.g.:
var image_url = window.baseurl + "Static" + image_path;
In AngularJS you would normally store that variable in the main app controller. If you only have one factory to access static resources, you could consider storing the baseurl there.
URL that starts with / is the URL from the root.
So if you set /Static/template.html, you can access template.html from both paths(www.mysite.com/ and www.mysite.com/system/).

CakePHP controller function with parameters doesn't show javascript

When I'm using controller function with parameters the rendered view just seems to forget every included .js files.
public function view($id = null) {
if(!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if(!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
If I take parameters away and put variable '$id = 1' on function the view with postID 1 renders okay in 'posts/view'.
I included javascript files to default.ctp in traditional way:
echo "script type='text/javascript' SRC='../js/jquery-1.9.1.min.js'></script>";);
(it includes '<' but this text editor won't me type it for safety reasons I guess)
I don't have knowledge about 'js helpers' of cakePHP. Can't I use javascript in traditional way?
Site renders okay in every other view (e.g. posts/add) and .js files are included in source code of 'posts/view/1'
The problem
You're using relative paths to the javascript;
<script src='../js/jquery-1.9.1.min.js'></script>
In this url, ../ means '1 directory up from the current location`, so when you're currently visiting this URL;
http://mysite.com/home/
Then your browser will correctly try to load the script from;
http://mysite.com/js/jquery-1.9.1.min.js
However, if you're visiting this url;
http://mysite.com/home/and/some/more/
Then the browser will look for the JavaScript here:
http://mysite.com/home/and/some/js/jquery-1.9.1.min.js
How to fix the problem
Use absolute paths for all 'assets' (CSS, JavaScript, Images);
src='/js/jquery-1.9.1.min.js'
Output the script-tags using CakePHP Helpers (after all, that's what they are meant for: to simplify your work :), e.g. echo $this->Html->script('jquery-1.9.1.min');

random images from a folder

I am trying to rewrite my code below to search a folder for all the images (they will be numbered but there maybe gaps, ie not 1.jpg,2.jpg,3.jpg but instead 1.jpg,15.jpg,60.jpg for this reason i would like to search the folder, put all the images into an array and then pick one randomly each time its looped.
Any help would be greatly appreciated.
Firstly i am currently specifying image total above the main script below:
imgWidth = 160,
imgHeight = 95,
imgTotal = 22,
total = 0,
tiles;
//create the HTML for the tiles and append that to the bg element
function makeTiles(count){
var html = '', imgNum;
while(count--){
imgNum = Math.floor(Math.random()*imgTotal + 1);
html += "<div class='tile' style='background:url(public/images/portfolio/all/"+imgNum+".jpg) 0 0 no-repeat;' ><img style='opacity:0; filter:alpha(opacity=0);' src='public/images/portfolio/all/"+imgNum+"-c.jpg' alt='' /></div>\r";
}
$bg.append(html);
}
You'll need to create a list of available images with something else than javascript, since it has no filesystem access, even though in the end, you are accessing the images via their url.
Workaround: enable some directory listing for the images, then access this page via javascript, parse the image files and construct an array out of them; but frankly, there are shorter and more robust ways to accomplish this ...
pseudocode ..
$ ls -1 *jpg > imagesfilelist.txt
$ cp imagefilelist.txt /some/publicly/accessible/folder
js/jquery ..
$.get("/some/publicly/accessible/folder/imagefilelist.txt", function(data){
alert("My image files: " + data);
});
...
javascript can not access local folders. point.
I repeat: there is no way you can "search folder" to get "array of images" in JS. You could do that part (server only!) in PHP or such server-side language and return results via AJAX.
To do what you want you need to know what the images are called. JavaScript cannot access folder directly as commented above. You would need to use a server side script to provide an array of the images for the JS to pick at random to do this.
Javascript will not be able to browse folders. What you need to do is to create an array of available images and then select a random one. You could do this using any server side technology (php, rails, java, .net ...).
The way you're trying to do it is a wrong one.But iwth a bit of tricks it could work though, but it's very wrong way to do this kind of things.
You can generate file list with php and feed it to your script. You can even create php script which will generate your script already populated with needed data but it's not the best to do this too.
So, the best ways are:
- create html with list of filenames/images(visible or invisible) by php, then manipulate it by javascript;
- create html and javascript wich will do AJAX query to php script which will return filename list(formated as JSON if you wish).
Why not upload your images to a free hosting site (like Flickr) grab the feed from your image group and select the random image from there?

Categories

Resources