简体   繁体   中英

How to execute a PHP function inside of a Javascript function?

I made a two PHP functions for my project, these two functions responsible for fetching different product category for different "online shop".

Now, I am implementing the function that when employee adding a new product, the employee first select which online shop does the new product belongs to (via a select), then depends on the online shop, the second select menu should display the correct options.

so, the first select looks like this

< Select name="Select_CCV_Webshop[]" id="ccv-webshop"        
onchange='loadNew_CCV_Category()'>

here I need help on how to execute /call /trigger the php function inside of method "loadNew_CCV_Category" .

Inside of function "loadNew_CCV_Category" , it will get the select value, and this value will be the parameters for the php function.

Please help :D, Thank you !!!!

You cannot execute php inside javascript . because php is server side program and javascript is browser related.

If you want to write php then you can try this.

alert("<?php echo 'hello' ?>")

or

$.ajax({
   url: 'yourphpfilepath.php',
   success: function(respon) {
   $('.result').html(respon);
 }
});

your code will be like this.

<Select name="Select_CCV_Webshop[]" id="ccv-webshop" onchange='loadNew_CCV_Category()'>
<div id=wheretoshowresult> </div>

<script>
function loadNew_CCV_Category(){
  $.ajax({
   url: 'yourphpfilepath.php', //url for your php function or file
   success: function(respon) {
    $('#wheretoshowresult').html(respon);
   }
  });
}
</script>

The short answer

You can not. PHP is executed server-side and only the PHP-generated page is then delivered to the browser, where JS takes over and can continue reacting to input, but only with information it already has.

The more helpful answer

You can, however, either deliver the information for both cases to the browser and decide which one should be shown, or, which in most cases will be what you would rather do, make another call to the server from within your JS.

That means you would have an additional PHP script, which executes the function and generates the page content you want to insert.

You would then access that script file using JS and insert the generated contents into your page.

As for how to do that, maybe this answer might help .

EDIT: Also refer to Avi's answer on that.

You can try this way,

<?php
function square($num)
{   
    echo $num * $num;
} 
?>

<select name="Select_CCV_Webshop[]" id="ccv-webshop"
onchange='loadNew_CCV_Category()'>
    <option>Select</option>
    <option>Test Php</option>
</select>

<script>
    function loadNew_CCV_Category(){
        var phpData = "<?php square(4) ?>"
        alert(phpData);
    }
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM