Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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";
}
?>
share|improve this question

closed as off-topic by user2864740, Felix Kling, Lazin, Frédéric Hamidi, Gustav Bertram Nov 27 '13 at 10:32

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance." – user2864740, Lazin
If this question can be reworded to fit the rules in the help center, please edit the question.

    
1  
Your answer probably lies in the answer to this question : stackoverflow.com/questions/7165395/… –  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 Answers 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 :).
share|improve this answer
    
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

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()}
share|improve this answer
    
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.