Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a variable in JavaScript with PHP echo function?

How do I define a variable in javascript with echo function, from the external php file?

We have theconfigfile.php, thejsfile.js and thephpfile.php.

In theconfigfile.php we have:

<?php
$path = 'http://example.com/home.php'; // Set your path
?>

In thejsfile.js we have:

... 
if (confirm("Are you sure you want to delete")) {
        $.ajax({
            type: "POST",
            url: "http://example.com/home.php",
            data: dataString,
            cache: false
        });
...

And in thephpfile.php we have:

    <php 
    include "theconfigfile.php";
    ?>

    <html>
    <head>
    <script type="text/javascript" src="thejsfile.js"></script>
    </head>

<body>
...here is the code that uses file thejsfile.js...
</body>
</html>

I used this method:

... 
if (confirm("Are you sure you want to delete")) {
        $.ajax({
            type: "POST",
            url: "<?php echo $path; ?>",
            data: dataString,
            cache: false
        });
...

Only works when javascript is part of the code. And if I use it external, like this...

<script type="text/javascript" src="thejsfile.js"></script>

...does not work! Solutions?


2 Answers

There are a couple of ways you can go about doing this.

You can configure your webserver to process files with extension .js with PHP and just inject your PHP there. Of course this means you need a way to actually calculate your variable there, and this would slow down serving your regular javascript content.

You can simply output the PHP variable to a Javascript variable within a <script> element like this

<script type="text/javascript">
var path = "<?php echo $path; ?>";
</script>

And then access this path variable in your AJAX. Most would probably use the second approach.

like image 164
Mike Brant Avatar answered Jan 25 '26 01:01

Mike Brant


You can rename your thejsfile.js to thejsfile.php, add the following to the very beginning of it, and it should be parsed for PHP:

<?php header("Content-type: text/javascript"); ?>

Then reference it like this:

<head>
<script type="text/javascript" src="thejsfile.php"></script>
</head>

Your other option is to just set your server up to parse .js files for PHP.

like image 41
HellaMad Avatar answered Jan 25 '26 01:01

HellaMad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!