0

I wan to call a PHP function in JavaScript code that echoes out a value:

<?php
function ex()
{
  $num=10;
  echo($num);
} 
echo '<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="<?php ex(); ?>";
    alert(x);
    return false;
  }
</script>'?>

However, it doesn't work. Can you help?

2
  • You're trying to call the function inside of a String. Commented Aug 10, 2014 at 12:16
  • 1
    For the love of all that is good, please do not put 'wanna' in your titles. Txtspk dz nt blg hr, thx! Commented Aug 10, 2014 at 12:31

6 Answers 6

1

Try this:

<?php
function ex()
{
  $num=10;
  echo($num);
} 
echo '<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="' . ex() . '>";
    alert(x);
    return false;
  }
</script>'?>
Sign up to request clarification or add additional context in comments.

Comments

1

Just try with:

...
var x="' . ex() . '";
...

Comments

1

Try echoing only what you need

<?php
function ex()
{
  $num=10;
  echo($num);
} 
?>

<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="<?php ex(); ?>";
    alert(x);
    return false;
  }
</script>

1 Comment

+1 for this. Using echo for large blocks of code is not a great (nor pretty) practice.
0
function ex()
{
    $num=10;
    echo $num;
    return $num; // if you want to get JS alert
}
echo '<script type="text/javascript">
function sam_click(clicked)
{
    var x='.ex().';
    alert(x);
    return false;
}
sam_click(); // if you want to get JS alert
</script>';

Comments

0

instead of echoing the $num, return it as a result and then append it in the script part.

<?php
function ex()
{
  $num=10;
  return ($num);
} 
echo '<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="' . ex() . '";
    alert(x);
    return false;
  }
</script>'?>

Comments

0

another solution with heredoc and nowdoc:

<?php

// helper to call functions as nowdoc
// example: {$fn( function() )}
function fn($functionCall) 
{
  return $functionCall;
}
$fn = 'fn';

function ex()
{
  return 20;
}

$js = <<<EOT
<script type="text/javascript">
  function sam_click(clicked)
  {
    var x="{$fn(ex())}";
    alert(x);
    return false;
  }
</script>
EOT;

echo $js;

Find more detail on PHPDoc:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.