1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95: 96: 97: 98: 99: 100: 101: 102: 103: 104: 105: 106: 107: 108: 109: 110: 111: 112:
<?php
class AjaxRequest implements View
{
const GET = 'get';
const POST = 'post';
const BEFORE_SEND = 'beforeSend';
const AJAX_SEND = 'ajaxSend';
const SUCCESS = 'success';
const AJAX_SUCCESS = 'ajaxSuccess';
const ERROR = 'error';
const AJAX_ERROR = 'ajaxError';
const COMPLETE = 'complete';
const AJAX_COMPLETE = 'ajaxComplete';
private $target;
private $method = self::POST;
private $events = array();
private $parameters = array();
public function __construct($target, $onsuccess, $onfailure = null)
{
$this->set_target($target);
$this->set_onsuccess_callback($onsuccess);
$this->set_onfailure_callback($onfailure);
}
public function set_target($target)
{
$this->target = Url::to_rel($target);
}
public function set_method($method)
{
$this->method = $method;
}
public function set_success_callback($onsuccess)
{
$this->add_event_callback(self::SUCCESS, $onsuccess);
}
public function set_failure_callback($onfailure = null)
{
if ($onfailure != null)
{
$this->add_event_callback(self::ERROR, $onfailure);
}
else
{
$this->add_event_callback(self::ERROR, 'function() {alert(\'ajax failure\');}');
}
}
public function add_event_callback($event, $callback)
{
$this->events[$event] = $callback;
}
public function add_param($key, $value)
{
$this->parameters[$key] = $value;
}
public function render()
{
$tpl = $this->get_template();
$this->assign($tpl);
return $tpl->render();
}
private function get_template()
{
return new StringTemplate('jQuery.ajax({
url: ${escapejs(TARGET)},
type: ${escapejs(METHOD)},
data: {# START param #{param.NAME}:{param.VALUE},# END #},
# START event #{event.NAME}:{event.CALLBACK},# END #
});');
}
private function assign(Template $tpl)
{
$tpl->put('TARGET', $this->target);
$tpl->put('METHOD', $this->method);
$events = array();
foreach ($this->events as $event => $callback)
{
$events[] = array('NAME' => $event, 'CALLBACK' => $callback);
}
$tpl->put('event', $events);
$params = array();
foreach ($this->parameters as $key => $value)
{
$params[] = array('NAME' => $key, 'VALUE' => $value);
}
$tpl->put('param', $params);
}
}
?>