GAD GAD - 6 months ago 14
PHP Question

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?

Answer

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.

Comments