ambe5950
ambe5950

Reputation: 75

passing php variable to separate javascript file

I have been reading how to pass variables from a php webpage to a separate javascript file, but am not having any luck.

Please don't mark this as duplicate, as I know there are a ton of things out there telling the ways to do this. I recognize those posts and am more just checking my syntax or seeing if there is anything unique about my specific situation that is causing those methods not to work.

So I have a PHP webpage where I POSTed some variables to:

DOCTYPE HTML

...

 <?php
            $id = $_POST["id"];
            $name = $_POST["name"];
    ?>
...

HTML code with some usage of PHP variables

javascriptFunction()

end page

Then in a separate javascript file I have:

var markerlocation = '<?php echo $point; ?>'; 

function javascriptFunction () {

alert("markerlocation");

});

This seems really straight forward, but for whatever reason I can't get it. I also have tried with json encode.

I can delete this when done. Sincere thanks for any help.

Upvotes: 0

Views: 572

Answers (2)

Jonathan Gray
Jonathan Gray

Reputation: 2609

You can point the script tag source to a .php file instead of a .js file, I think that's what you want. Works with image tags too ;)

Edit: some browsers may require the text/javascript mime header in order for it to work properly, but it's not hard with PHP I'll assume you already know how to do that.

On a side note: This option should probably only be used if you're planning on allowing the client to cache the javascript output. If you don't want the client to cache it, you need to set additional headers.

Upvotes: 0

Parfait
Parfait

Reputation: 1750

My way:

  1. Declare a Array to store variable for passing variable to JavaScript
  2. Encode the Array to JSON in php
  3. Decode the JSON String from php and store as a JavaScript variable

PHP

<?php
    //You may declare array for javascript
    $jsVal = array(
        'user_name' => 'Peter',
        'email' => '[email protected]',
        'marker_location' => '102,300'
    );
?>  

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>var phpConfig = jQuery.parseJSON(<?=json_encode($jsVal)?>);</script>

Separated javascript file

alert(phpConfig.marker_location);

You can try it

Upvotes: 2

Related Questions