-1

I was wondering if its possible to have a .php file with all the functions:

    <?php 
    function 1(){
      do something
    }
    function 2(){
      do something
    }
    function 3(parameter){
      do something with parameter
    }
    ?>

and then in the javascript code, i need to call the php function like:

function someFunction(parameter){
   call PHP function3(parameter)
}

I know i must use AJAX, but I can't get any example of that.

Thanks in advance.

Meph
  • 1
  • 1

2 Answers2

3

You can't call a PHP function with Ajax. You can only make a request to a URL.

It is up to your PHP to interpret that request as one which means it should call a function.

e.g.

$.post("/call/function1.php");

where function1.php looks something like this:

<?php
    include "myFunctions.php";
    function1();
?>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-2

javascript is client side and you can't call php function directly. the best way is use ajax to send request to php file and get response but if you locate to other way can do it :

create .php file and write php code and javascript both of them in this file like this :

<?php 
function yourPhpFunction($param){//do stuff} 
?> 
function yourJsFunction(param){
   var response=<?php yourPhpFunction('input')?>
}
 //and do other js or php code

then load this php file in script tag on project frontend page like :

<script src="myfile.php"></script>

this is very bad way but it is worked and sometime is very useful

  • 1
    That won't work. It will call `yourPhpFunction('input')` when the JS is generated, not when `yourJsFunction` is called. Also most browsers will reject it because the server will say it is an HTML document and not JS (because you forgot to override the default content-type) – Quentin Jul 08 '21 at 16:01