base_url doesn't work in external js and css file - php

I was trying to call "base_url()" inside of an external .js file.
my 'test.js' file path is "js/test.js".
my test.js code was:
function download(s){
var w=window.open('<?php base_url(); ?>home/download?f='+s+'.ogg','Download','height=100,width=100');
}
And I linked that file(my js file is working fine when trying simple JavaScript codes) :
<script src="<?php echo base_url(); ?>js/test.js" type="text/javascript"></script>
But that always said that the access was denied and asked for server permission.
I tried 'site_url()' too, even I tried just an echo "hello" in 'download' function but those didn't work. But when I add that code inside of header.php view file like:
<script type="text/javascript">
function download(s){
var w=window.open('<?php base_url(); ?>home/download?f='+s+'.ogg','Download','height=100,width=100');
}
</script>
Then that worked.
And in case of external CSS when I write:
background:url('<?php base_url(); ?>images/side.png');
That doesn't work. But if I write:
background:url('../images/side.png');
Then that works.
So how can I call "base_url()" inside of external .js file and .css file ?

You can't call base_url() in a javascript / css file.
You need to put a relative path in these js/css files.
PHP scripts aren't aren't run unless they're in a .php file.

For Using This Solution Just Keep in mind that you have to put the Script tag before the external js script.
<script type="text/javascript">
var baseURL = "<?php echo base_url(); ?>";
</script>
Now Use baseURL variable in that external js.

Related

Correct path to resources

I'm having trouble with the path when a file calls a css or a js file.
I'm using Codeigniter also Smarty template engine. My base URL is> http://local.project
My css and js files are located in> project/site/assets/css and project/site/assets/js
The thing is that when I call the resources from the view the path is a mess and not found error appears.
I have tried many ways but still can't make it. I begin to think that this can be a path problem from Codeigniter. I mean.. maybe I'm missing something that I can't figure what is.
When I do an inspection with the browser I can see that this is set by default>
http://local.project/
and then from the view I call it like>
<script type="text/javascript" src="{site_url()}assets/js/jquery.flot/jquery.flot.js"></script>
but the path that is built is>
http://local.project/%7Bsite_url()%7Dassets/js/jquery.flot/jquery.flot.js 400 (Bad Request)
I'm driving crazy here, any help would be very appreciated!
try:
<script type="text/javascript" src="/assets/js/jquery.flot/jquery.flot.js"></script>
or
<script type="text/javascript" src="/js/jquery.flot/jquery.flot.js"></script>
can you provide your ip,to view the page?
Try using base_url() instead of site_url().
try:
<?php
echo "<script type='text/javascript' src='" . base_url() . "assets/js/jquery.flot/jquery.flot.js'></script>" ;
?>
To use the base_url() you need to call in your controller the URL helper:
$this->load->helper('url');
Then in your view:
<script type="text/javascript" src="<?php echo base_url();?>assets/js/jquery.flot/jquery.flot.js"></script>
First of all load the url helper
$this->load->helper('url');
secondly get base address using this
echo base_url();
and finally your base address is "http://local.project", no slash at the end, so try this
<script type="text/javascript" src="<?php echo base_url();?>/assets/js/jquery.flot/jquery.flot.js"></script>
and make sure your base address do not have any extra characters, like space or enter
I could make it. Just opened my Smarty.php file and changed this line view/admin just to views
$this->setTemplateDir(APPPATH.'views');
After that the url I could use from the view is
<script type="text/javascript" src="assets/js/jquery.flot/jquery.flot.js"></script>

Inserting php into js file

I have a loading gif for the gallery on my website. In my js file I have this code to show the loader:
image: $("<img src='images/loading.gif'/>"),
Currently this the image isn't appearing because I haven't put the full image path. But instead of putting the full image path, I would prefer to do this:
<img src="<?php bloginfo('url');?>/images/loading.gif”>
But I can't work out how to make this php work in my js file. How do I go about doing it in the easiest way?
I prefer to..
1) In my header include (the php include that contains any <head> data), write a small
inline JS function that creates a global object containing any variables I need from the server (PHP). I can use the 'echo' and 'json_encode' functions here because its in an inline JS snippet in a php file.
2) You could write a JS function inside your JS file that uses AJAX to call a PHP file, which will return the same JSON encoded data as number 1, then you parse it and assign in to a global variable.
Both essentially do the same thing, except with 2 you are using AJAX, which will add an additional request. I prefer option 1, because it is done along with the pages execution. Option 2 may require you to wait until the DOM is ready, depending on various aspects of your program (in which I can not tell).
Option 1 requires inline JS, but you really shouldn't harp on this, as with dynamic websites it can actually be a plus, as along as it is short and concise. Some people get on others about inline JS. Don't let them yell at you.
I am not totally sure what you are trying to do. But if that JS isn't working, why not including a php file, or just writing some php in the header, that includes the JS inside it in 'echo()'. I.e:
echo('?><img src="<?php bloginfo('url');?>/images/loading.gif" /><?php');
Correct me if I am misunderstanding your intent.
You can't place PHP code directly into a .js file, but you could have some javascript in the head element of your PHP file right before including the javascript file.
In this javascript you could then define variables and assign data to them using PHP. These variables would then be accessible from inside the javascript file.
<head>
<script type='text/javascript'>
var _g_bloginfo = "<?php echo '...'; ?>";
</script>
<script type='text/javascript' src='javascript.js'></script>
</head>
A cleaner technique for passing PHP data to JavaScript is to store the data in data attributes which you can then access via JavaScript. As a simple example:
<body data-home-url="<?php echo home_url(); ?>">
You can access that in jQuery like:
var home = $('body').attr('data-home-url');
FYI you can use json_encode to convert PHP object/arrays into a JSON objects which you can read via $.parseJSON or JSON.parse. WP's wp_localize_script can actually do this for you, but note that in that case it'll expose the converted data to the window.
You can create a php file instead (of your js file with all the code you already have in that js file + references to your php variables/functions) and include that in your main php file.
Example html:
<?php $example = 23; ?>
<html>
<head><title></title>
<script type="text/javascript">
<?php include('js.php'); ?>
</script>
</head>
<body></body>
</html>
js.php:
var a = <?= $example ?>;
alert(a);
will eventually output:
<html>
<head><title></title>
<script type="text/javascript">
var a = 23;
alert(a);
</script>
</head>
<body></body>
</html>

How to add JavaScript dynamically in Opencart?

I want use a jQuery plugin in category.tpl. Put files in javascript/jquery directory. Now, how can use this plugin?
/* one can load JS like that: */
if(file_exists('catalog/view/javascript/'.$this->config->get('config_template').'/script.js')) {
$this->document->addScript('catalog/view/javascript/'.$this->config->get('config_template').'/script.js');
}
It is rather "the proper way" to use existing functions, than to add scripts manually into header.tpl.
As a hint, based upon the answer below - one could loop an array of filenames, in order to keep control over the loading order, which is often relevant while they might depend on each other.
I've never used OpenCart, but a quick google session tells me that you should include the plugin scripts (just like any other js) in a file called header.tpl.
Here is a part of an sample header.tpl-file I found:
<script type="text/javascript" src="catalog/view/javascript/jquery/jquery-1.3.2.min.js"></script>
Just add a the following line below the jQuery include so it looks like this:
<script type="text/javascript" src="catalog/view/javascript/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="catalog/view/javascript/jquery/[PLUGIN FILE NAME].js"></script>
and you should be good to go.
First paste your jquery files, css files and images in catalog/view/javascript/yourplugin folder.
Then call the jquery plug in files in catalog/view/theme/yourtheme(default)/template/product/category.tpl file.
For ex,
YOur php code;..
...
....
<script src="catalog/view/javascript/jquery/jquery-ui-min.js"></script>
<script type="text/javascript" src="catalog/view/javascript/jquery/jquery.anythingslider.js"></script>
<link rel="stylesheet" href="catalog/view/theme/default/stylesheet/anythingslider.css">
<script>
// DOM Ready
$(function(){
$('#slider').anythingSlider();
$('#slider1').anythingSlider();
$('#slider2').anythingSlider();
});
</script>
its for slider.. you can do your action in php (above the script).
You'll need to include JS and CSS sources in Header View (/catalog/view/theme/[your theme]/template/common/header.tpl)
in config.php
define('DIR_JAVASCRIPT', 'D:\wamp\www\opencart/view/javascript/your_dir/');
in header.tpl
<?php
if (is_dir(DIR_JAVASCRIPT)):
if ($handle = opendir(DIR_JAVASCRIPT)):
while (false !== ($file = readdir($handle))):
if (preg_match('#\.js$#', $file)):
?>
<script type="text/javascript" src="<?php echo 'view/javascript/your_dir/'.$file; ?>"></script>
<?php
endif;
endwhile;
closedir($handle);
endif;
endif;
?>

Calling a view within a view not working properly

<script src="<?php echo site_url('bootstrapper/jqTimer'); ?>"></script>
So I've tried to call the controller below using the script above but I get error not found. Any ideas as to why this method is not working?
function jqTimer() {
$this->load->view("jquery.timers.js");
}
When loading javascript with a <script> tag, the src attribute is expecting a file name to a js file. You're giving it a path to a controller method in your CI install.
What you need to do is put the jquery.timers.js file in the public_html folder and access it from there:
// assuming you have the script in a [javascripts] folder inside [public_html]
<script src="<?php echo site_url('javascripts/jquery.timers.js'); ?>"></script>
If you'd prefer to load your javascript through views, then you need to do this instead:
<script><?php echo $this->load->view("jquery.timers.js", "", TRUE); ?></script>
This will echo out the contents of the view file between the <script> tags for embedded javascript. (passing TRUE as the third parameter returns the content of the file, so you can echo it out)
I don't see any reason why you should create a function in the controller just to load a javascript file.
The base_url() function can already do what you want.
<script src="<?php echo base_url('path/to/jquery.timer.js'); ?>"></script>
Have a look at the documentation for the URL helper
You're looking to echo out a link to the js, not echo out the js itself.
You could create a MY_Controller in the core folder which extends CI_Controller, in which:
function jqTimer() {
return site_url("jquery.timers.js");
}
Then, in any other controller (which extends MY_controller) you'd go:
$data['js_timer'] = $this->jqTimer();
/* proceed to load main view with $data */
View:
<script src="<?php echo $js_timer; ?>"></script>
This is DRY in that, should you decide to use a different js timer plugin, you need to replace it in one place only: the MY_Controller class (as opposed to every view file).
Still, a bit of an odd way of doing things...

PHP within .JS file

I would love to post some starting code in this question, but to be honest, I' stumped.
I'm looking for a way to use PHP within my .JS file.
I would like to be able to use real PHP functions inside my "stuff.js" and then be able to include it using:
<script type="text/javascript" src="whatever.js"></script>
Any thoughts? Thanks.
<script src="/YOUR_PHP_FILE_PATH/file.php"></script>
Also add header in php file
header(Content-Type: text/javascript);
You just have to write your JavaScript into a php file and then include it
<script type="text/javascript" src="whatever.php"></script>
I would recommend you keeping your JS functions in a .js file and the variable data that needs to be output dynamically could be output directly in the main php/html file:
<script type="text/javascript" language="JavaScript">
var a = "<?php echo addslashes($a); ?>";
// ...
</script>
Other possibility would be to tell your server to proccess *.js file with php but I wouldn't recommend that as it could cause some unexpected problems.
It's impossible but you can use PHP file as a JavaScript file talking in a short way. ;)
<script type="text/javascript" src="whatever.php"></script>
And in whatever.php:
<?php
echo "var text = 'test';";
?>
alert(text);

Categories