Welcome Guest, Not a member yet? Register   Sign In
Question : Best practice - PHP code in javascript
#1

[eluser]Crafter[/eluser]
I generally place my javascript functions in directories off my top level directory, as in

-> system
-> application
-> images
-> js


Recently, my web applications have been using more and more intelligent processing. For example, where previously my javascript was mainly to achieve form validation and clever browser tricks, nowadays, what with Ajax and all, I am moving more and more of my traditional view code into JavaScript.

So, it is therefore not uncommon to see URLS and other application paths in my JavaScript code.

However, with the code existing off my application directories, there is no opportunities to inject PHP code like base_url() into them.

What innovate ways do others solve this issue.
#2

[eluser]gunter[/eluser]
you could put the javascript into a view, you can use all the benefits of Ci (base_url, configs, whatever) and then save the parsed view into your /javascript folder...
just an idea Smile
#3

[eluser]Crafter[/eluser]
Yes that's true, gunter,

Mostly I needed site and base URLS, so I avoided that.

I was looking at syntax like the following:
Code:
<script type="text/javascript" src="scriptaculous.js?load=effects"></script>

But I'm not sure how this is used inside the script. Anybody?
#4

[eluser]Sector[/eluser]
Hmm, you could do 2 things:

1) Make Apache recognize the .js extension as a php file. (search in apache or php config, I don't know, for .php / .php4 / ..., and add .js)

Then you can just use <?=base_url()?> etc in your .js file, because it will be parsed as php, your javascript code will be untouched, as it will interpreted as html (just as in views)

2) Turn your .js file into a .php file, I don't know if browsers will take that kind of stuff though Smile

Hope it helps
#5

[eluser]xwero[/eluser]
I don't know if it will work but you could try make placeholders in your javascript file like [baseurl]/img/test.jpg and add a hook to the pre_system to a function where you replace [baseurl] with the actual value.

I've never tried it myself but seeing your question got me thinking. If it works you could do the same for css files.
#6

[eluser]esra[/eluser]
You can use the js.php file extension to distinquish the file as a javascript file with PHP code, then include your PHP functions and variables as necessary.

You can also take opposite path and wrap javascript code in PHP helper functions, plugin functions or class methods.
#7

[eluser]xwero[/eluser]
i tried my proposed solution and it did work but i would had to know the pre_system hook is called with every request so you need to set a variable in a different, one value, file.

Code:
// hook class
class Pre_system
{
    function js()
    {
        $path = substr(__FILE__,0,strpos(__FILE__,'system'));
        $url = 'http://'.$_SERVER['SERVER_NAME'].str_replace('index.php','',$_SERVER['SCRIPT_NAME']);    
        $placeholder = file_get_contents($url.'placeholders.txt');
                if($placeholder == 0 || $placeholder != $path)
                {
                    $content = str_replace('[baseurl]',$url,file_get_contents($url.'js/test.js'));
            file_put_contents($path.'js\test.js',$content);
                    file_put_contents($path.'placeholders.txt',$path);
                }
    }
}
// config/hook.php
$hook['pre_system'] = array(
                                'class'    => 'Pre_system',
                                'function' => 'js',
                                'filename' => 'pre_system.php',
                                'filepath' => 'hooks'
                                );
With this code you can replace your site and it still gets the right url.

This code is only proof of concept code so there are some improvements you need to add.

I don't know if the javascript files with the extension .php will be cached as eagery by the browsers as the .js extension files.
#8

[eluser]ekeretex[/eluser]
I usually add a hidden field to my view file like:
Code:
<form>
<input type="hidden" name="siteurl" id="siteurl" value="<?php echo site_url(); ?>" />
</form>

And in my javascript file:
Code:
var siteUrl = document.getElementById("siteurl").value;

or if I'm using the excellent prototype library,
Code:
var siteUrl = $F("siteurl");
#9

[eluser]Colin Williams[/eluser]
There is no best practice for a bad practice. You Ajax should all be on a separate layer that reads paths from the base HTML/PHP file (form action values, link href values, etc).

Code:
<a id="next-page" href="&lt;?= site_url('pages/next/'. $page->id) ?&gt;">Next page</a>

Code:
nextLink = document.getElementById('next-page');
nextLink.onClick = function(){
   request.setUrl(this.getAttribute('href'));
   response = request.send();
   ...
};
#10

[eluser]xwero[/eluser]
I think ekeretex offered the best solution yet but i don't like the use of an extra html element.

If i would go the javascript way i would use a vars.js file where i store the urls. it would be like a configuration file for the javascript code. This way you can add any file or library you want.




Theme © iAndrew 2016 - Forum software by © MyBB