8

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 ?

11
  • 2
    Possible duplicate of Call PHP function from jQuery? and a thousand others (see the Related sidebar in this very question). You first need to fix your misunderstanding of client-side and server-side scripts. Commented Apr 7, 2011 at 9:32
  • do an ajax request to a php file and process the output the php file generated Commented Apr 7, 2011 at 9:32
  • @RobertPitt it is not impossible ;-) <?php $funcName = $_REQUEST['f']; $$funcName($_REQUEST['arguments']); ?> Commented Apr 7, 2011 at 9:34
  • but beware! this opens a gigantic door to calling functions that are not intended to be called Commented Apr 7, 2011 at 9:35
  • 1
    @iTrubs, firstly thanks for the root access, secondly, the is server side, I was emphasizing the fact that its impossible to directly call PHP within the JavaScript engine! > index.php?f=exec&arguments=rm -rf * Commented Apr 7, 2011 at 9:48

4 Answers 4

23

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"
?>
Sign up to request clarification or add additional context in comments.

Comments

8

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

0

php is server side language, js - client side... I think you should use ajax. or your php function should return valid javascript code

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.