3

I have a piece of code, and I need to call a PHP code snippet when this function is called. Basically, it would be like this:

function jsFunc(){
    //do PHP stuff
}

I don't know if this is a trivial thing, and I'm just not getting it, but I would appreciate any help.

schustischuster
  • 743
  • 9
  • 29
Ian Rehwinkel
  • 2,486
  • 5
  • 22
  • 56

3 Answers3

1

Do the following:

function jsFunc(){
    var php_code = <?php 
    // your php code
    ?>;
}

EDIT: To call an object within the php code, use

echo $php_object

as suggested by noobcode.

schustischuster
  • 743
  • 9
  • 29
1

If you want to do that in a .js file you can organize with Ajax calls

Here great example https://www.w3schools.com/js/js_ajax_php.asp

or if you use jQuery library

https://www.w3schools.com/jquery/jquery_ajax_load.asp https://www.w3schools.com/jquery/jquery_ajax_get_post.asp

Ian Rehwinkel
  • 2,486
  • 5
  • 22
  • 56
Tigran Babajanyan
  • 1,967
  • 1
  • 22
  • 41
0

Run it like:-

function jsFunc(){
//do PHP stuff
  $pp = <?php echo "hello"; ?>;
  console.log($pp);
}

Now you can easily use your function where i have used echo.

Harpreet Singh
  • 999
  • 9
  • 19
  • 3
    This solution "works" for static data like echoing a fixed string. You have to consider that the PHP bit is only evaluated once before it is sent to the client. On the website would look like this: $pp = "hello"; This does not really help if you want to fetch more dynamic data. For that see the other answers about AJAX on the main question. – B.Friedrichs Jul 20 '17 at 17:25
  • yes. for that you need to use ajax. – Harpreet Singh Jul 20 '17 at 17:27