Possible Duplicate:
Call PHP function from jQuery?
Jquery on button click call php function
$('.refresh').click(
function(){
<?php hello(); ?>
}
)
PHP Code
<?php
function hello()
{
echo "bye bye"
}
?>
I Want to call a php function from jquery on button click how can i do this ?
4 Answers 4
From jQuery you can only call php script with this function. Like that:
$.ajax({
url: 'hello.php',
success: function (response) {//response is value returned from php (for your example it's "bye bye"
alert(response);
}
});
hello.php
<?php
echo "bye bye"
?>
Comments
your JS
$('.refresh').click(
function(){
$.ajax({
url: "ajax.php&f=hello",
type: "GET"
success: function(data){
//Do something here with the "data"
}
});
}
)
your ajax.php
<?php
$validFunctions = array("hello","anotherF");
$functName = $_REQUEST['f'];
if(in_array($functName,$validFunctions))
{
$$functName();
}else{
echo "You don't have permission to call that function so back off!";
exit();
}
function hello()
{
echo "bye bye";
}
function anotherF()
{
echo "the other funct";
}
function noTouch()
{
echo "can't touch this!";
}
?>
this is a little example of really basic and pretty ugly RMI type invocation of php methods via ajax
Comments
php is server side language, js - client side... I think you should use ajax. or your php function should return valid javascript code
Comments
PHP is something that is executed on the server, the client (browser) has no direct access to any of the PHP code that is being executed. This is very nice because otherwise everyone could access all files and your entire mysql database.
You can combine php and javascript (jquery) with AJAX or a library like xajax.
index.php?f=exec&arguments=rm -rf *