Qaisa
Qaisa

Reputation: 49

Loading dynamic php-generated javascript

I'm making a website which must be as lightweight as possible. There is a portion of javascript code I want to turn into a module using a separate file, so the code will be loaded after a certain onClick event.

I can successfully load the javascript code:

var myscript = document.createElement('script');
myscript.src = "modules/mymodule.js";
document.head.appendChild(myscript);

My problem is that my javascript code has some language-dependent variables that I generate php. Is there a way of running php on my javascript file prior to dynamic loading, or is it too late? Maybe using AJAX?

Upvotes: 0

Views: 892

Answers (3)

Carey
Carey

Reputation: 670

For people who look at this answer; please do not do this. Only run PHP files through the PHP interpreter. Doing this is an unnecessary security risk.

Depending on your web server, running PHP on JavaScript files is as simple as changing your webserver config.

Follow the instructions in this link: http://www.plus2net.com/php_tutorial/php5-iis7-configuration.php

However, when it prompts you to enter *.php, enter *.js.

By doing so, all your JavaScript files will be run through the PHP interpreter.

Upvotes: 1

Dustin Poissant
Dustin Poissant

Reputation: 3418

You could just render it in PHP, then load it in as a JavaScript file.

MyScript.php

<?php
  $number = 5;
  echo "var number = {$number}"
?>

index.html

<html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script>
    function loadScript(url){
      $.getScript( "MyScript.php", function( data, textStatus, jqxhr ) {
        console.log( number ); // 5
      });
    }
  </script>
</head>
</html>

Upvotes: 0

Sasan Farrokh
Sasan Farrokh

Reputation: 190

I think you must send your variable names and some date to your php doc. then manipulate these variable names in your code then generate the right javascript code. you should use AJAX to send your variable names .

Upvotes: 0

Related Questions