Calling a class method using jQuery AJAX?

I am migrating from xajax PHP AJAX library to jQuery AJAX.

With xajax, I could contain all my AJAX calls inside class methods, linking public class methods with javascript function names (e.g. $ this-> registerFunction ('javascriptFunctionName', & $ this, 'classMethodName')).

I hope there is a way to do something like this 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 use AJAX for MVC controller methods, but unfortunately my legacy product doesn't use MVC :-(

Please tell me is there a way?

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

+2


source to share


2 answers


To compose what the stripe says, you can make a really simple ajax controller and deploy 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 ofcourse parameters and maybe do a nice rewrite in htaccess / vhost so you can use urls like / ajax / class / method? ... but you get the general idea. You probably want to have some kind of valid callbak registry so that you don't just call any valid php calls ... which could be dangerous :-)

+2


source


JQuery doesn't define how your server (PHP) should work. It just makes an xhr http request to the url you give it. You will have to come up with your own convention for how you want your server to respond.

In my PHP applications, I usually check $ _SERVER ['HTTP_X_REQUESTED_WITH'] and then process the jquery request like any other request.



if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&  $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
    // handle ajax request
}

      

+2


source







All Articles