Tópicos em Setembro, 2007

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)

PHP:
  1. /*
  2. JAXHelper - CakePHP Helper for Ajax with jQuery
  3. Author: Tulio Faria (www.tuliofaria.net)
  4. Requeriments:
  5. - jquery: http://docs.jquery.com/Downloading_jQuery
  6. - jform (for some features like observeForm): http://jquery.com/plugins/project/form
  7. Using:
  8. - include jquery.js and jquery.form.js in your view (yes, using plain html or html helper :) )
  9. - include the helper Jax in your controller
  10. - call any of methods available: link, observeField and observeForm
  11. */
  12.  
  13. class JaxHelper extends Helper {
  14.  
  15. var $helpers = array("Html");
  16.  
  17. function link($text, $url, $target, $options = null, $loading = null){
  18. $aId = 'link' . intval(rand());
  19. $url = $this->Html->url($url);
  20. $att = " ";
  21.  
  22. if (is_array($options)){
  23.  
  24. foreach($options as $k=>$v){
  25. $att.=$k.'="'.$v.'" ';
  26. }
  27.  
  28. }
  29.  
  30. echo "<a id="\" href="http://www.tuliofaria.net/%5C%22$url%5C%22">$text</a>";
  31. echo $this->_jsBlock("\$(\"#$aId\").click( function(){  \$.post(\"$url\", function(data){
  32. \$(\"$target\").html(data); }); return false; }); ");
  33. }
  34. function observeField($element, $options){
  35. $event = $options["event"];
  36. $update = $options["update"];
  37. $url = $this->Html->url($options["url"]);
  38.  
  39. $code = $options["loading"].'
  40. $.ajax({
  41. type: "POST",
  42. url: "'.$url.'",
  43. data: $("'.$element.'").serialize(),
  44. success: function(data){
  45. $("'.$update.'").html(data);
  46. '.$options["complete"].'
  47. }
  48. });
  49. ';
  50.  
  51. return $this->_jsBlock($this->_addReady("\$(\"$element\").$event(function(){ $code })"));
  52. }
  53.  
  54. function observeForm($element, $options){
  55. $event = $options["event"];
  56. $update = $options["update"];
  57. $url = $this->Html->url($options["url"]);
  58.  
  59. $code = '$("'.$element.'").ajaxSubmit({
  60. target:        \''.$update.'\',
  61. beforeSubmit:  function(){'.$options["loading"].'},
  62. success:       function(){'.$options["complete"].'}
  63. }
  64. );';
  65.  
  66. return $this->_jsBlock($this->_addReady("\$(\"$element\").$event(function(){ $code return false; })"));
  67. }
  68.  
  69. function _jsBlock($content){
  70. return "<script type="\">$content</script>";
  71. }
  72. function _addReady($content){
  73. return "\$(function(){ $content } );";
  74. }
  75.  
  76. function test(){
  77. echo $this->_jsBlock($this->_addReady("alert(\"Jax Helper has been installed and ready to use!\");"));
  78. }
  79. }
  80. ?>

Exemplos:

Link:

PHP:
  1. link("Click Here!", "/contatos/info/1/", "teste", "teste"); ?>

Observe field:

PHP:
  1. $options["event"] = "change";
  2. $options["update"] = "#teste";
  3. $options["url"] = "/contatos/info/1/";
  4. $options["loading"] = "$('#loading').fadeIn('slow');$('#teste').hide();";
  5. $options["complete"] = "$('#teste').fadeIn('slow');$('#loading').fadeOut();";
  6. echo $jax->observeField("#texto", $options); ?>

ObserveForm:

PHP:
  1. $options["event"] = "submit";
  2. $options["update"] = "#teste";
  3. $options["url"] = "/contatos/info/1/";
  4. $options["loading"] = "$('#loading').fadeIn('slow');$('#teste').hide();";
  5. $options["complete"] = "$('#teste').fadeIn('slow');$('#loading').fadeOut();";
  6.  
  7. echo $jax->observeForm("#testando", $options); ?>

Em breve publicarei exemplos mais decentes de uso.

Qualquer sugestão ou dúvida, comente!

Abraços,

Comentários (14)

Eu te ajudei? Que tal me ajudar?

Olá pessoal,

esta semana estava pensando sobre um assunto interessante: Minha conta do Dreamhost está vencendo :( a qual possibilitou eu colocar os vídeos tutoriais... :)
Não tão interessante assim né? rs...

Na verdade este post é para as boas almas que desejarem ajudar de alguma forma o blog... O link para doação está disponível  do lado esquerdo do blog, quem quiser doar usando o PagSeguro (do UOL) é só clicar lá... Quer ajudar de outra forma? Entre em contato comigo...

Claro que a ajuda será bem vinda tanto para o blog quanto para mim :) Vocês sabem como é né? Vida de universitário é uma tristeza :)
Abraços,

Comentários (12)