-1

I have created a button which will call a JS function div_show()

 echo '<div id="requestsample"><a name="1"  onclick="return div_show(\''.$search_result['serviceid'].'\');" href="#1">';

This function will pass serviceid to JS.JS function will then call the PHP function add() to execute it.

<script>
 function div_show($a) {
 document.write($a);
 document.write(' <?php add($a); ?> ');
}
</script>

 <?php
function add($a)
{
 echo $a;
//code for calculation
}
?>

PHP add function will exceute this statement only when I pass a specific numeric value.It is not dynamically taking the value of $a

2 Answers2

1

I think you need to clear your confusion before writing your code further> Javascript is a client side programming language it means Javascript is compiled by your browser , But In the other hand PHP is server side programming language means server compiled your php code and then return the output as html,json,xml

 <script>
 function div_show($a) {
 document.write($a);
 document.write(' <?php add($a); ?> ');
}
</script>

So in the above code as it is a javascript code it will compiled by the browser and when it find this line ' <?php add($a); ?> ' as it don't understand php output as a string as a result nothing will happen

So Now the question is how you will solve the issue as soon as you click the button you need to make a server request with a query parameter so that the script check the condition and run the function and out put the add value as html

quick example suppose php script name is a.php where your add() method exist

New Javascript will be

<script>
 function div_show($a) {
   window.location.href = "/a.php?q="+$a;
}
</script>

In a.php

<?php
if(isset($_GET['q'])){
 $a = $_GET['q'];
  // run your add($a) method
}

?>
Achyut Kr Deka
  • 739
  • 1
  • 8
  • 18
0

PHP is not real-time. when you visit a php file, the php interpreter convert php to html. when you use JavaScript to add php code into html, the php interpreter no longer work.Thus you can not implement what you want.

Yao Yuan
  • 350
  • 3
  • 11