Reputation: 1771
exactly as title says, I need to put php inside of the javascript that is echoed by php
ex:
<?
echo ('<script language="javascript" type="text/javascript">
if (something) then (some php)')
?>
thats not real code just might help get the idea and please note the best way to do what im trying is this way, if its possible.
Upvotes: 1
Views: 306
Reputation: 1
Output the <script>
tag like this:
<?php
function run_javascript($script_code){
print "
<script language='javascript'>
<!--
$script_code
// -->
</script>
";
}
run_javascript(" alert('I´m javascript here!'); ");
?>
Upvotes: -1
Reputation: 11148
You can't do that, PHP is a server-side language, that means it renders when the page loads and not after that.
The solution can be to call a PHP via AJAX, that PHP can have the case conditions and then it will render what you want.
Example:
The javascript (using jQuery):
$(".yourbutton").click(function(event){
event.preventDefault();
$.post("yourPHP.php", {var: somethingdynamicpassedviajavascript},
function(data){
//get ther result
$("#yourdiv").html(data);
}, "html");
});
What this does is place a click event into something with a class named "yourbutton", and when you click that, it will call an external PHP via an AJAX post, sending a var (in this example), you can send something dynamic, change the "somethingdiynamicpassedviajavascript" with some var.
PHP (yourPHP.php):
$myvar = $_REQUEST['var'];
//do your cases here:
switch ($myvar) {
case "1":
echo "this is for the case 0";
break;
case 1:
echo "this is for the case 1";
break;
}
Here you get that var, and depending on the case, send a different output. Notice that this may need to add a test for POST and other anti-vandalism methods...
Upvotes: 5
Reputation: 513
if you're trying to dynamically create a javascript based on some conditions you're looking for something link this:
<script language="javascript" type="text/javascript">
<?
if ($something == $somethingelse)
{
echo 'var something = 10;';
}
else
{
echo 'var somethingelse = 25;';
}
?>
</script>
if you're to execute php-code via javascript ... that can't really be done, at best you can use PHPjs to emulate php-functions.
Upvotes: 0
Reputation: 2098
yes you can do that.. your php scirpt generates/echoe the javascript code in your html page. You just need to play with single and double quotes and escape them properly In large scripts this is quite messy - better to put your js code in a seperate js file
Upvotes: 0
Reputation: 1232
u may try this
<?php
echo ('<script language="javascript" type="text/javascript">
if (something) then (some php)')
echo ('</script>');
?>
Upvotes: -3