Embedding php in javascripts

I tried to inject some PHP into a javscript function that is called from onChange in a drop down list. the javascript function is in the .js file, I can force the DDL to call the function, however I cannot make this function work with php ... in the end I am going to use the value selected in DDL to access the DB and fill in other fields from there, right now I'm trying to get it to work with php:

    function controllerType(){

       alert('outside php');
       <?php
       $message = "inside php";
       echo "alert('$message');";
       ?>

     }

The function prints the first warning, but not the warning called in php.

+3
source share
6 answers

Your web server is probably not looking for PHP code in the .jsdefault files . You will need to say that you need to look for PHP in these files or change the file extension to .php.

, - Apache, .htaccess:

AddHandler application/x-httpd-php .js

+4

function controllerType() {
    alert('outside php');
    alert('<?php echo $message; ?>');
}
+1

alert() PHP.

PHP -, JavaScript JavaScript.

, , JavaScript. CodePad.

0
<?php
   $message = "inside php";
?>
<script type="text/javascript">
function controllerType(){
       alert('outside php');
       alert(<?=$message;?>);
     }
</script>
0

, , javascript PHP. , , .php .htaccess( , apache), php .js

0

:

In the end, I'm going to use the value selected in DDL to access the database and fill in other fields from there

It looks like you are trying to run PHP code at runtime in a browser. PHP is a server-side language and you cannot just use it in a javascript file as you try.

You need the javascript function to output the value from the drop-down list to the PHP page through an HTML form or through AJAX.

Forgive me if I misunderstood you.

0
source

All Articles