-2

I want to call a PHP function from javascript, I know that´s impossible by natural ways, because PHP runs in the server and javascript in the client. I have heard that AJAX is used for this sort of function, and I wanna know if somebody could help me with the syntax. For example I wanna call the PHP function print from javascript:

<html>
<body>
<a href="#" onclick=js()></a>
</body>
</html>

<script type="text/javascript">
function js(){
//Call print function
}
</script>

<?php
function print(){
echo "Hello World";
}
?>
Agmp
  • 1
  • 1
  • 6
  • http://www.w3schools.com/php/php_ajax_php.asp – Corey Ogburn Nov 26 '13 at 23:18
  • 1
    Your answer probably lies in the answer to this question : http://stackoverflow.com/questions/7165395/call-php-function-from-javascript – Erik Nov 26 '13 at 23:19
  • Lots of tutorials can. Once there is an problem stemming from an attempt .. then we might have a question. – user2864740 Nov 26 '13 at 23:19
  • thanks about the tutorials, there is the answer to my question, if I have a more specific question I will return – Agmp Nov 26 '13 at 23:30

2 Answers2

2

You cannot directly "call a PHP function" this is just no possible. What you can do is to call a PHP script that will generate the result for you. So what you want to do is:

  1. Write the PHP script that generates your data.
  2. Find out how to call a PHP script from JavaScript (for example here http://api.jquery.com/jQuery.ajax/).
  3. Call the script using AJAX and feel good for learning a new thing today :).
Jan
  • 2,295
  • 1
  • 17
  • 16
  • Thanks for the help. I knew I couldn´t "call the PHP function", and Ajax is exactly what I needed for this issue. – Agmp Nov 26 '13 at 23:33
0

You can use different ways to reach the point. For example you can send name of the function from ajax and then call php [eval] method1. That's the worst idea. Forget about it.

The better idea to send some parameter, that corresponds to "print" method. And in php use

if ($input_param == 1) {print()}
Andrii Horda
  • 170
  • 1
  • 16
  • Thanks for the help. The print method was just an example of what I needed to do. I have already found out how to do it. – Agmp Nov 26 '13 at 23:34