0

I want to make some thing like this

my-php-file.php

  $lang = 'es';

my-js-file.js

if ($lang == es)
   {
   something-magical-happens;
   }

or like this:

if (URL == www.mydomain.com/index.php?lang=es)
   {
   something-magical-happens;
   }

3 Answers 3

3

you could generate js on-the-fly

my.js.php:

<?php echo "//Yes." ?>
var i = "<?php echo $_GET['lang']; ?>";

function doSomethingWithI(){
  alert(i);
}

Now, try to include

<script type="text/javascript" src="my.js.php?lang=es"></script>

in your html and you'll see :)

Edit: Check it in action here: http://h.kissyour.net/so/phpjs/

Edit: Edited example on my server to closer resemble what I wrote here.

Edit: Oh yes. Don't forget to clean your code!

Sign up to request clarification or add additional context in comments.

7 Comments

Don't forget the quotes around <?php echo $_GET['lang']; ?> and the semicolon after. The semicolon is not required but will cause problems if the script is minified ;)
I'm confused, shouldn't it be my.php.js? Are you including a php file with a javascript "src statement" (<script type="text/javascript" src="my.js.php?lang=es"></script> ), is that possible?
try it and you'll see :] and no, my.js says its js (for you) and .php tell server to parse it with php first :)
I tried it and I added 'localhost/tests/js-php/index.php?lang=es' to the URL, but nothing happened.
janoChen: last 10 mins I played with quick demo - check edit ;)
|
0

In this specific case, why not simply properly set the document language and then look at that using JavaScript?

<html lang="es">

And in the script:

if (document.documentElement.getAttribute('lang') === 'es') { alert('Spanish'); }

Comments

0

You can – as the accepted answer indicates – generate entire javascript files with PHP. But if you are just trying to access some limited dynamic content, this is often overkill. If you are just trying to access a few variables that need to be PHP generated, inline javascript works fine. Add this to your HTML's head:

<script type="text/javascript">
  <?php if( $condition == true ) : ?>
    var variable1 = <?php $var1 ?>,
        variable2 = <?php $var2 ?>;
  <?php else: ?>
    var variable1 = <?php $var1Alt ?>,
        variable2 = <?php $var2Alt ?>;
  <?php endif; ?>
</script>

Just make sure you add this before any linked scripts depend on these variables.

Comments

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.