1

I'm trying to use a PHP variable for a string into my Javascript code. However I'm not getting the expected result.

I refuse to use JQuery, I do prefer using pure Javascript even if it needs more work.

This is my PHP file: script.php

<?php

    $filename = "./about.txt";
    $doc = file_get_contents($filename);

    echo $doc;

?>

It runs ok within my PHP.

I've tried this on my action.js file:

function get_about() {

    var text = "<?php echo $doc ?>";

    document.getElementById("div2").innerHTML = text;
}

I would appreciate any help. I'm new to web programming. I did a research but it didn't help.

Pedro del Sol
  • 2,840
  • 9
  • 39
  • 52
Telmo Vaz
  • 189
  • 1
  • 2
  • 11
  • 1
    Please let us know what output you are seeing and what is the expected output? There is no way to help without knowing what you are looking for? – pal4life Sep 20 '13 at 14:17
  • 3
    If it's in a file called _action.js_, I assume the web server is not set up to parse _.js_ files as PHP like it is with _.php_ files. – Wiseguy Sep 20 '13 at 14:19
  • 1
    As an aside, why do you _refuse_ to use jQuery? – Wiseguy Sep 20 '13 at 14:20
  • 1
    Possible duplicate of http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines – JRizz Sep 20 '13 at 14:21
  • You are right. The output for my JS code in the way I'm doing that is none. No variable is printed. My alone php output is ok, and my javascript output (alone) is ok if there's another kind of output that is not the variable that came from php. SO I think there should be a problem with one file linking the other, but I don't know why – Telmo Vaz Sep 20 '13 at 14:26
  • If the JavaScript doesn't work — What does the **JavaScript** look like? The PHP doesn't matter. – Quentin Sep 20 '13 at 14:26
  • J.Robertson, that is with JQuery and I don't want to use is. The reason why is that I think Jquery is more for designers. As a programmer, I think I should have the obligation to understand all that I am doing. And this is the reason why I prefer C to Java. It's an opinion and a personal taste. – Telmo Vaz Sep 20 '13 at 14:29
  • My javascript code is up there and is just that – Telmo Vaz Sep 20 '13 at 14:30
  • What are you trying to achieve here? You clear on what file_get_contents does? Read here http://php.net/manual/en/function.file-get-contents.php if you really need this? Update with what you exactly need to do on thi? – pal4life Sep 20 '13 at 14:39
  • You might as well want to use Ajax. See here for a pure JS example http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first – Mina Sep 20 '13 at 14:54
  • 2
    I would argue that jQuery is more for efficient programmers. jQuery is still Javascript, it just makes it easier to write good javascript code. Also I just clicked the link I posted...how do you claim that's for jquery? All the code in that question is pure javascript... – JRizz Sep 20 '13 at 14:54
  • @TelmoVaz — "My javascript code is up there and is just that" — so you are passing `""` to the browser as JavaScript without running it through a PHP interpreter then? – Quentin Sep 20 '13 at 19:30
  • @TelmoVaz Please follow up on your question and tell us if you have found the answer. – Mohammed Joraid Dec 20 '13 at 03:32

7 Answers7

1

You can't use PHP variables in Javascript files because PHP works on the server while the JS works in client.

What you can do is generate javascrit code on PHP files and work with this code on javascript files.

Ex:

index.php

<?php
    $nameUser = "Marc";
    ...
    ...
    echo '<script type="text/javascript">';
        echo "var name = $nameUser;";
    echo '</script>';
    echo '<script type="text/javascript" src="/action.js" />'
?>

action.js

alert("Hello " + name );

This is not the prettiest way to do this, but the idea is there.

Hope that helps you

jam0ral3s
  • 534
  • 4
  • 9
  • The line `var name = $nameUser;` will literally set the value of `name` to `$nameUser`, which will probably throw an error in the browser, since this isn't a valid Javascript literal. What you need to change it to is `echo "var name=" . $nameUser . ";"` – hkk Jan 03 '14 at 03:27
0

Sorry, you cant mix PHP and Javascript that way.

  • PHP on the server produces an HTML page, with javascript,
  • THEN the browser reads the pages and run the JAVASCRIPT.

So PHP can't use Javascript, viceversa Javascript acts after PHP, and Javascript can use PHP.

MaxV
  • 588
  • 1
  • 4
  • 13
0

Well, as others said, you cannot mix JS with PHP. This is Client/Server architecture where both are separated.

I don't know about your case, but if you are printing JS from php (means from the same .php page) then your approach might work depending on what you need.

But since your JS is on a separate files. Then it will be executed only when it's loaded by the client's browser.(is this what you want?)

Once the code is on the client browser, it cannot see what's on the server. The only way to get some data from the server is by initiating a request to pull the data thru AJAX request (i suppose there are other ways, but i'm limiting my self to your case).

Therefore we have two cases.

Case 1 : Seperate JS from PHP and put it in a separate file.

Example script.php

<?php

    $filename = "./about.txt";
    $doc = file_get_contents($filename);

    echo $doc;

?>

. . action.js

 //using pure js ajax request 
    function get_about() {

   var ajaxRequest;
    try {
        ajaxRequest = new XMLHttpRequest();
    } catch (e) {
        try {
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {
                alert("Connection lost. Please try again.");
                return false;
            }
        }
    }
    ajaxRequest.onreadystatechange = function() {
        if (ajaxRequest.readyState == 4) {
             document.getElementById("div2").innerHTML = ajaxRequest.responseText;
        }
    }    
    ajaxRequest.open("GET", "script.php");
    ajaxRequest.send(null);                            
    }

Case 2 : Both JS and PHP are located on the same file, mean JS will be printing along with PHP code and sent all together to the client's browser.

Method 1: open javascript tag and put ur js code there

Example script.php

<?php
    $filename = "./about.txt";
    $doc = file_get_contents($filename);
    echo "<script>
           function get_about() { 
              document.getElementById("div2").innerHTML = '{$doc}'
            }
          </script>";        
?>

Note that putting $doc into a js string might break down if it contains (",',>,<,\,/)depending on your html.

Method 2: combination of the previous approaches. Assign data to JS varibale and access it from JS file. In this way you can still have your separate JS file

Example script.php

<?php
    $filename = "./about.txt";
    $doc = file_get_contents($filename);
    echo "<script>
           var doc = '{$doc}'//global variable
          </script>";        
?>

action.js

 //using pure js ajax request 
    function get_about() {
      document.getElementById("div2").innerHTML = doc ;

    }
Mohammed Joraid
  • 6,202
  • 2
  • 27
  • 38
0

I know this is a 3 month old question, but I came across it and thought that I can give something helpful.

If you want to pass this variable to the JS script, then the following code will work:

script.php

<?php
  $filename = "./about.txt";
  $doc = file_get_contents($filename);
  echo $doc;
?>
<script type="text/javascript">
  var text = "<?php echo $doc ?>";
</script>
<script src="action.js"></script>

action.js

function get_about() {
  document.getElementById("div2").innerHTML = text;
}

Explanation

Most servers with standard configurations don't treat .js files, and for that matter, any non-.php files the same way as .php files. Unless you have some custom configuration set up, you can't put <?php PHP code here ?> in script.js. So, in your code you gave, the value of the javascript variable text was equal to the string "<?php echo $doc ?>".

Luckily, the only way to use scripts isn't by using external scripts, but you can use inline scripts with the <script> tag. The PHP interpreter will go through any code inside a .php file and look for these - <?php ?> - then interpret them, which is why inline scripts in a php file work the way they do.

hkk
  • 2,069
  • 1
  • 23
  • 48
0

Just use json_encode:

var text = <?php echo json_encode($doc); ?>;
Ultimater
  • 4,647
  • 2
  • 29
  • 43
-1

Give this a shot including a semicolon

function get_about() {
    var text;

    text = "<?php echo $doc; ?>";

    document.getElementById("div2").innerHTML = text;
}

Working example here http://ideone.com/FLduOl

pal4life
  • 3,210
  • 5
  • 36
  • 57
  • Sir @MarkRijsmus I beg to differ, I tested this script and it works. The question is about getting the script to work, not where to place it. So please delete your comment since its misleading. – pal4life Sep 20 '13 at 14:30
  • Your example works because the JS is in the same PHP file, whereas it sounds like the asker's JS is in a separate file called _action.js_. – Wiseguy Sep 20 '13 at 14:48
  • He also mentions that he is new to web programming and he is looking to get the expected result(value) so this serves as an example in that case along with how to use the function with a semicolon in it for the php – pal4life Sep 20 '13 at 14:50
  • Very true. Add or link to a thorough explanation _why_ the original doesn't work and why yours does, and I'll upvote you. (BTW, the semicolon [isn't technically required](http://www.php.net/manual/en/language.basic-syntax.instruction-separation.php) there, though it may be good practice anyway.) Asker needs to learn, so teach. :-) – Wiseguy Sep 20 '13 at 15:00
-2

In your head sections place this code:

<script type="text/javascript">
    var text = "<?php echo $doc ?>";
</script>
<script type="text/javascript" src="/action.js" />

Now you can use the value of text within your action.js.

Mark Rijsmus
  • 627
  • 5
  • 16