Neekoy
Neekoy

Reputation: 2533

Passing a PHP variable into a Javascript function

I have a PHP variable that I am declaring upon loading the page, and want to use it in a JavaScript/jQuery function that loads upon a button click.

I have the following on my index.php page:

// Creating a random name for a file and creating it. Working properly.
$fname = substr(md5(rand()), 0, 7);
$file = fopen("temp/" .$fname, 'w');

And when I click a button, the following JavaScript function should run:

//Use the generated filename in the JavaScript function
var fname = <?php echo $fname; ?>;
var fileName = "temp/" + fname;

My understanding is that the PHP variable is outside of the scope of the JavaScript function, since I believe this is the way it should be done.

Can you please help with this?

Upvotes: 0

Views: 93

Answers (4)

Martin Lietz
Martin Lietz

Reputation: 113

The problem is the missing apostroph like anant kumar singh mentioned. I tested the following code in a webpage:

<?php
        $fname = substr(md5(rand()), 0, 7);
        $file = fopen("temp/" .$fname, 'w');
    ?>
    <html>
    <head
    </head>
    <body>
    <script>
        var fname = "<?php echo $fname; ?>";
        var fileName = "temp/" + fname;
    </script>
    </body>
</html>

Upvotes: 1

user3780225
user3780225

Reputation: 141

I think you need an extension on your filename:

$extension = ".txt";
$fname = substr(md5(rand()), 0, 7).$extension;
$file = fopen("temp/" .$fname, 'w');

Upvotes: 1

marianis
marianis

Reputation: 21

Try do this. in a php file of course.

var fname = '<?php echo $fname; ?>';   

Upvotes: 1

Rob Foley
Rob Foley

Reputation: 581

PHP generates a page and presents it to a browser. As far as the browser is concerned, by the time the page is received, PHP is finished. So to answer your question, that should work, since PHP will essentially just spit out the text on to the page, which will act as normal. That is, unless I am terribly misinformed.

The "scope" of a PHP variable is long gone by the time Javascript gets to run, so that isn't really an issue.

Upvotes: 3

Related Questions