How to add a PHP script to a .js file?

Suppose I have an external JavaScript file named myJavascript.js which has 3 functions like the following:

function myFunc1(){
    //some code
}

function myFunc2(){
    //some code
}

function myFunc3(){
    //some code
}

Now, I want to add some PHP script in myJavascript.js like the following, and it's from a separate PHP file named myView.ctp:

<?php
$url = Router::url($this->here, true);
$url = explode('/', $url);
$baseURL = $url[0] . '//' . $url[2] . '/' . $url[3] . '/' . $url[5];
$baseURL2 = $url[0] . '//' . $url[2]. '/' . $url[3];
?>

Why I need to add this PHP script inside myJavascript.js is this - I want to use the PHP variables $baseURL and $baseURL2 inside the 3 functions I've created.

How can I achieve this?

Edit:

I'm sorry I actually made a mistake in my question. The php view file is actually named as myView.ctp, as it's a CakePHP view file. The extension is .ctp and not .php. I've updated my question accordingly.

Upvotes: 1

Views: 729

Answers (3)

floriank
floriank

Reputation: 25698

I would definitely not do that but instead passing the args to methods or properties.

We usually have one script that takes care of initialization, lazy loading other stuff and so on. This is done in the layout.

<header>
<script src="/js/app.js">
<script>
    app.init(<?php echo json_encode($this->request); ?>);
<script>
</header>

Just make sure you pass only what yo need of the request, it might contain security related data, so be careful by passing the whole thing.

In your specific views:

<script>
    app.nameSpaceForView.someMethod('<?php echo $someStringVar; ?>');
</script>

You can even avoid this by implementing some logic in the above app.init() function that will check if app.controllers.ControllerName.ViewName is set based on the passed request info and if it's present execute it.

You won't need much, in the best case any, JS in your views by this.

Upvotes: 0

Endre Simo
Endre Simo

Reputation: 11541

You cannot use php variables inside a separate javascript file. Instead what you can do is either to include the script inside the php template like

<script type="text/javascript">
....
</script>

or either to parse the url via javascript if this fits for you. You can get the current url with:

window.loacation.href

then you can parse the string as you wish.

Upvotes: 0

Radonirina Maminiaina
Radonirina Maminiaina

Reputation: 7004

It's possible if you work into an internal HTML file and the extension is php. Into your myView.php You can declare a global variable, and assign a response server value, into that file. For example:

myView.php

<script>
    var globalVar = <?php echo "your_value" ;?>
</script>
<script src="external_file.js"></script>

external_file.js

console.log(globalVar) // your_value

Upvotes: 1

Related Questions