404 Not Found
404 Not Found

Reputation: 1223

How to call class's method using jquery Ajax call

i am newbie in Jquery and Ajax.. Please bear with my stupid problem..

i am trying to call method say test() inside class hello through ajax call..

hello.php

class hello
{
      public function test()
      {
        //some data
      }

      public function abc()
      {
        //some data
      }
}

now i want to call test() from another php file...

for example:

b.php

  $.ajax({
    url : 'hello.php->test()', //just for example i have written it bcz it should call only test() not abc()..
   })

is it possible to call it directly? i have went through $.ajax() api but i din't found anything helpful..

All answer will be appreciates...

Upvotes: 2

Views: 6197

Answers (2)

Stefan
Stefan

Reputation: 3900

One approach is to pass the name of the class, the constructor arguments, and the method name and arguments etc. via ajax POST or GET, for example:

var url = 'callMethod.php';
var data = {
    str_className: 'Hello',
    arr_consArgs: {arg1: 'test1'},
    str_methodName: 'test'
};
$.post(url, data, function(response) {
    etc.
});

In PHP script named callMethod.php:

/* Place your 'Hello' class here */

// class
$str_className = !empty($_POST["str_className"]) ? $_POST["str_className"] : NULL;
if ($str_className) {
    // constructor
    $arr_consArgs = !empty($_POST["arr_consArgs"]) ? $_POST["arr_consArgs"] : array();

    // method
    $str_methodName = !empty($_POST["str_methodName"]) ? $_POST["str_methodName"] : NULL;
    if (!empty($str_methodName)) {
        $arr_methodArgs = !empty($_POST["arr_methodArgs"]) ? $_POST["arr_methodArgs"] : array();
    }

    // call constructor
    $obj = fuNew($str_className, $arr_consArgs);

    // call method
    $output = NULL;
    if (!empty($str_methodName)) 
        $output .= call_user_func_array(array($obj, $str_methodName), $arr_methodArgs);

    // echo output
    echo $output;

}

where:

function fuNew($classNameOrObj, $arr_constructionParams = array()) {
    $class = new ReflectionClass($classNameOrObj);
    if (empty($arr_constructionParams))
        return $class->newInstance();
    return $class->newInstanceArgs($arr_constructionParams);
}

Upvotes: 1

codefreak
codefreak

Reputation: 7131

Try this:

hello.php

class hello
{
      public function test()
      {
        //some data
      }

      public function abc()
      {
        //some data
      }
}
if(isset($_GET['method'])){
   $hello = new hello;
   $hello->$_GET['method']();
}

b.php

 $.ajax({
    url : 'hello.php?method=test', //just for example i have written it bcz it should call only test() not abc()..
   })

By they way, it's not secure to expose your class via ajax requests.

Upvotes: 1

Related Questions