1

I have a Javascript file with the code I need to run my PHP project, but since it's a .js file I can't embed the PHP variables (such paths, config variables etc...) using the the <?php ... ?> way.

So I thought that one possible way would be using AJAX requests or a REST API.

Then two questions came in my mind:

  1. Could that lead to some performance issues? - I have to wait the server's response so I guess it's yes.
  2. Which are the possible alternatives?

Edit:

The config variables are stored in a PHP class for easy access from the PHP code. If you can tell me a better way I would really appreciate it.

8
  • 1
    You could add all your variables as a json string or whatever to your HTML page and access them with JS. Commented Dec 30, 2013 at 21:40
  • Performance issues don't really come to mind if you're just grabbing a PHP variable, it's basically instantaneous (depending on the server speed...I guess my point was it's not like your querying the DB for a massive amount of data) Commented Dec 30, 2013 at 21:40
  • Right now I have a file that is included in the HTML head which acts as communication between the PHP and javascript, so I can have the heavy work in javascript in a separated javascript.js. However this is not the best as I'm mixing PHP, HTML and javascript in just few lines, so good question +1 Commented Dec 30, 2013 at 21:40
  • Well, actually I'm doing just what Chris suggests here. Commented Dec 30, 2013 at 21:44
  • possible duplicate of Passing PHP variable into JavaScript Commented Dec 30, 2013 at 21:44

2 Answers 2

2

You can put the following in your .htaccess file, then your javascript files should be able to compile php inside js.

<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Sign up to request clarification or add additional context in comments.

Comments

0

You could create a php file that outputs javascript and use php code inside it:

<?php header('Content-Type: application/javascript'); ?>
alert('<?php echo "test"; ?>');

3 Comments

And now the question is: Will that work with RequireJS? I don't know but i can try it (and I will tomorrow).
The browser will see it as a javascript file, so if including a js file from the server works with RequireJS this should too.
Yep, I know that, but I'm not sure how RequireJS configuration will do. I'll let you know if it works :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.