Reputation: 45
I was trying to embed some PHP into a javscript function that gets called from an onChange in a drop down list. the javascript function is in a .js file, I can get the DDL to call the function, however i cannot get the function to work with the php... eventually i am going to use the value selected in the DDL to access a DB and populate other fields from there, right now i am trying to get it to work with the php:
function controllerType(){
alert('outside php');
<?php
$message = "inside php";
echo "alert('$message');";
?>
}
The function prints the first alert but not the alert called in the php.
Upvotes: 3
Views: 120
Reputation:
<?php
$message = "inside php";
?>
<script type="text/javascript">
function controllerType(){
alert('outside php');
alert(<?=$message;?>);
}
</script>
Upvotes: 0
Reputation: 6720
Try the following
function controllerType() {
alert('outside php');
alert('<?php echo $message; ?>');
}
Upvotes: 1
Reputation: 2322
From your following sentence:
eventually i am going to use the value selected in the DDL to access a DB and populate other fields from there
It really sounds like you are trying to have the PHP code execute at runtime within the browser. PHP is a server side language and you cannot simply use it in a javascript file as you are trying to.
You will need to have the javascript function post the value from the drop down list to a PHP page through a HTML form or through AJAX.
Forgive me if I misunderstood you.
Upvotes: 0
Reputation: 7061
I think the problem might be that your javascript is not being evaluated by your PHP parser. You might have to create a separate document for that function which ends in .php or using a .htaccess (assuming you're using apache) to tell your php handler to parse .js files
Upvotes: 0
Reputation: 475
Your webserver probably isn't looking for PHP code in .js
files by default. You'll have to tell it to either look for PHP in those files or change the file extension to .php
.
If you you want to try the former and you're running an Apache web server, try adding the following line to your .htaccess
file:
AddHandler application/x-httpd-php .js
Upvotes: 4