JAX - jQuery Ajax Helper for CakePHP
Olá pessoal,
intediado com o helper do cake que trabalha com prototype? Eu também...
Então resolvi criar (inicialmente para uso próprio) o JAX - jQuery Ajax Helper. Que funciona de forma bem semelhante ao helper nativo do cake, mas com algumas melhorias...
O código pode ser visto abaixo: (e baixado aqui)
-
/*
-
JAXHelper - CakePHP Helper for Ajax with jQuery
-
Author: Tulio Faria (www.tuliofaria.net)
-
Requeriments:
-
- jquery: http://docs.jquery.com/Downloading_jQuery
-
- jform (for some features like observeForm): http://jquery.com/plugins/project/form
-
Using:
-
- include jquery.js and jquery.form.js in your view (yes, using plain html or html helper
) -
- include the helper Jax in your controller
-
- call any of methods available: link, observeField and observeForm
-
*/
-
-
class JaxHelper extends Helper {
-
-
-
$url = $this->Html->url($url);
-
$att = " ";
-
-
-
foreach($options as $k=>$v){
-
$att.=$k.'="'.$v.'" ';
-
}
-
-
}
-
-
\$(\"$target\").html(data); }); return false; }); ");
-
}
-
function observeField($element, $options){
-
$event = $options["event"];
-
$update = $options["update"];
-
$url = $this->Html->url($options["url"]);
-
-
$code = $options["loading"].'
-
$.ajax({
-
type: "POST",
-
url: "'.$url.'",
-
data: $("'.$element.'").serialize(),
-
success: function(data){
-
$("'.$update.'").html(data);
-
'.$options["complete"].'
-
}
-
});
-
';
-
-
return $this->_jsBlock($this->_addReady("\$(\"$element\").$event(function(){ $code })"));
-
}
-
-
function observeForm($element, $options){
-
$event = $options["event"];
-
$update = $options["update"];
-
$url = $this->Html->url($options["url"]);
-
-
$code = '$("'.$element.'").ajaxSubmit({
-
target: \''.$update.'\',
-
beforeSubmit: function(){'.$options["loading"].'},
-
success: function(){'.$options["complete"].'}
-
}
-
);';
-
-
return $this->_jsBlock($this->_addReady("\$(\"$element\").$event(function(){ $code return false; })"));
-
}
-
-
function _jsBlock($content){
-
return "<script type="\">$content</script>";
-
}
-
function _addReady($content){
-
return "\$(function(){ $content } );";
-
}
-
-
function test(){
-
echo $this->_jsBlock($this->_addReady("alert(\"Jax Helper has been installed and ready to use!\");"));
-
}
-
}
-
?>
Exemplos:
Link:
Observe field:
-
$options["event"] = "change";
-
$options["update"] = "#teste";
-
$options["url"] = "/contatos/info/1/";
-
$options["loading"] = "$('#loading').fadeIn('slow');$('#teste').hide();";
-
$options["complete"] = "$('#teste').fadeIn('slow');$('#loading').fadeOut();";
ObserveForm:
-
$options["event"] = "submit";
-
$options["update"] = "#teste";
-
$options["url"] = "/contatos/info/1/";
-
$options["loading"] = "$('#loading').fadeIn('slow');$('#teste').hide();";
-
$options["complete"] = "$('#teste').fadeIn('slow');$('#loading').fadeOut();";
-
Em breve publicarei exemplos mais decentes de uso.
Qualquer sugestão ou dúvida, comente!
Abraços,
