Search code examples
phpjquery

Calling a class method with jQuery AJAX?


I am moving from the PHP AJAX library xajax to jQuery AJAX.

With xajax, I could contain all my AJAX calls inside class methods by binding public class methods to javascript function names (eg. $this->registerFunction('javascriptFunctionName', &$this, 'classMethodName')).

I am hoping there is a way I can do something similar with jQuery AJAX, whereby I can do something like this:

$('#myButton').click(function() {
    $.get('class|methodName',
    {
      parameter: value
    },
    function(data) {
      if (data) {
        ...
      }
      else {
        ...
      }
    });

    return false;
  });
});

I know you can AJAX calls to MVC controller methods, but unfortunately my legacy product doesn't use MVC :-(

Please tell me there is a way?

If not, is there a way to map a call to a global PHP function?


Solution

  • To piggyback on what lane is saying you might want to make a really simple ajax controller and rout everything to it:

    <?php
    class AjaxController {
    
    protected $_vars = null;
    protected $ajax = null;
    
    
    public function __construct()
    {
      $this->_vars = array_merge($_GET, $_POST);
      $this->_ajax = (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&  $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')
      $this->_response = null;
    }
    
    public function process()
    {
      if($this->isAjax()){
        if(isset($this->_vars['method']) && isset($this->_vars['class'])
        {
           $callback = array($this->_vars['class'], $this->_vars['method'];
        } elseif(isset($this->_vars['function'])){
          $callback = $this->_vars['function'];
        } 
    
        if(isset($callback) && is_callable($callback))
        {
           $this->_responseData = call_user_func($callback, $this->_vars);
           $this->sendResponse(200);
        } else {
           $this->_responseData = 'UH OH';
           $this->sendResponse(500);
        }
    
    
      }
    }
    
    public function sendResponse($httpStatCode = 200){
    
      // set headers and whatevs
      print $this->_response;
      exit;
    }
    
    } // END CLASS
    
    $contoller = new AjaxController();
    $controller->process();
    

    youd want to do some filtering on the params of ofcourse and probably make some nice rewriting in htaccess/vhost so you can use urls like /ajax/class/method?... But you get the general idea. You would probably want to have some kind of valid callbak registry to so youre not just calling any valid php callable... that could be dangerous :-)