How to encrypt JavaScript code?

What is the conventional way to refactor JavaScript code to remove PHP templating code?

  • I'm trying to factor out some code from my main index.php file. If I factor the javascript into a .js file and include it using <script type="text/javascript" src="ext.js">, the php will not run. Currently I'm putting the javascript in a .php file and using php include to include it. Is there a cleaner way to do this?

  • Answer:

    In this day and age, I would try to separate your template code and logic completely from your JavaScript. All data that needs to be read by JavaScript should exist on the page in HTML. It's a little hacky, but you can do this by creating a hidden div somewhere on your page with the necessary information: <div id="UserInfo" data-user-email="<?= $userEmail ?>" data-user-name="<?= $userName ?>" > </div> Then, in your JavaScript (jQuery assumed for demonstration purposes): $(function () { var userName = $('#UserInfo').attr('data-user-name'), userEmail = $('#UserInfo').attr('data-user-email'); window.alert('Hello, ' + userName); });

Kelly Sutton at Quora Visit the source

Was this solution helpful to you?

Other answers

It's not the best way to complish this, try to set a data object which will be used in your javascript code, here is a sample: <html> <head> </head> <body> Your page content. <script type="text/javascript"> var _data = { userEmail: "<?=$userEmail ?>", userName: '<?=$userName ?>', messages: [ { title: "title", body: 'body'}, { title: 'title', body: 'content'} ] }; <script src="myjs.js" type="text/javascript"> //here should be your external js file content. //So we can get the value from php. var userName = window._data.userEmail; </script> </script> </body>

Shaca Ma

Your external javascript-generating file could be doing two things. A) because it has extension .js, the webserver never passes it to php for interpretation, so it just renders your php code intermingled with javascript, leaving you with invalid javascript that doesn't run. You either need to rename the file to ext.js.php, or add a webserver config rule telling it to interpret .js files as php in that particular directory. B) because it is generated in php, it is served with mime type of text/html instead of text/javascript, which could cause problems in some browsers - you should make sure to serve the right headers with the file from php.

Anton Stroganov

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.