Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Ajax and ExpressionEngine

Ajax and ExpressionEngine

A347386377e120e3230403d2558c1a0d?s=128

Lodewijk Schutte

October 23, 2009
Tweet

Transcript

  1. Ajax & ExpressionEngine || CodeIgniter The Hi road & the

    Low road EECI2009, October 23rd, Leiden, The Netherlands
  2. Hi! I’m Low! Lodewijk Schutte @low

  3. None
  4. None
  5. http://www.flickr.com/photos/jmspool/163305616/

  6. AJAX = Asynchronous JavaScript and XML

  7. Ajax = refreshing part of the web page

  8. None
  9. None
  10. It’s everywhere!

  11. <a  href="javascript:loadFile('myFile.txt')">Show  info</a> <a  href="myFile.txt"  onclick="loadFile(this.href);  return  false;">Show  info</a> <a

     href="delete.php?id=5"  onclick="return  confirm('Are  you  sure?');">Delete  this  item</a>
  12. None
  13. http://www.flickr.com/photos/mn_francis/418496408/

  14. Use Progressive Enhancement - Make sure your site works without

    the fancy stuff - Use unobtrusive JavaScript to make it better - Use the back-end for heavy lifting - Keep it accessible
  15. Hijax Plan Ajax from the start, implement Ajax at the

    end
  16. http://www.flickr.com/photos/andrewandsarah/185203822/

  17. - Identify design elements that imply the use of Ajax

    - How will it work without JavaScript? - How will it affect the back-end code? - And always ask yourself... Taking the Hi(jax) road
  18. None
  19. - Add, don’t take away - Use the correct methods:

    GET vs. POST - EE peeps: know what EE is doing or expecting - Keep It Simple... What are you doing?
  20. None
  21. None
  22. Example #1: Toggle Stock

  23. - Show form to logged in user - Create script

    to update entry - Use Ajax for quick responsiveness - Update stock indicator on screen Toggle Stock, the plan
  24. {exp:weblog:entries  weblog="wines"}  <div  class="item">    <table>      ...  

         <tr>          <th  scope="row">Stock</th>          <td  class="stock">In  stock</td>        </tr> ...    </table>    {if  logged_in}      <form  class="togglestock"  action="{path=ajax/togglestock}"  method="post">        <fieldset>          <input  type="hidden"  name="entry_id"  value="{entry_id}"  />          <button  type="submit">Toggle  stock</button>        </fieldset>      </form>    {/if}  </div> {/exp:weblog:entries}
  25. $_SERVER['HTTP_X_REQUESTED_WITH']  ==  'XMLHttpRequest' Using a library? Try this: Available in

    jQuery, MooTools, Prototype, Dojo...
  26. None
  27. None
  28. None
  29. Example #2: Quick Search

  30. - Hijack existing search form - Get results in JSON

    format - Generate HTML from result set - Catch errors Quick Search, the plan
  31. None
  32. None
  33. {   "results":  [  {exp:search:search_results}     {    

      "url"   :  "{url_title_path=wines/bottle}",       "title"   :  "{title}"     }{if  count  !=  total_results},{/if}     {/exp:search:search_results}   ],     "url"         :  "{path=wines/search/{segment_3}}",   "keywords"       :  "{exp:search:keywords}",   "total_results"   :  "{exp:search:total_results}" }
  34. {   "results"  :  [] }

  35. None
  36. None
  37. Example #3: Contact Form

  38. - Hijack existing mailto: links - Get contact form from

    server - Display form as modal window (lightbox) - Send form using Ajax Contact Form, the plan
  39. None
  40. None
  41. None
  42.   init  :  function()  {     //  Create  container

     div  for  lightbox     this.container  =  new  Element('div',{       'id'   :  'lightbox',       'load'   :  {         onSuccess:  this.loaded.bind(this),         onFailure:  this.failed.bind(this)       }     });     //  Create  transparent  overlay  for  lightbox     this.overlay  =  new  Element('div',{       'id'   :  'overlay',       'styles':  {'opacity':0.5},       'events':  {'click':this.close.bind(this)}     });     //  Add  event  to  links     $$('#primary  a').each(function(a){       if  (a.href  ==  'mailto:'+this.email)  {         a.addEvent('click',this.open.bindWithEvent(this));       }     },this);   },
  43.   open  :  function(event)  {         //

     Cancel  event     event.preventDefault();     //  add  data  container  and  overlay     this.container.inject(document.body);     this.overlay.inject(document.body);     //  place  container  50px  below  browser  chrome     this.container.setStyle('top',  50  +  window.getScroll().y);     //  add  loading  message  to  container     this.container.set('html',  '<p  id="loading">Loading</p>');     //  Load  url  into  data  container     this.container.load(this.url);   },
  44. loaded  :  function()  {   //  define  variables   var

     form,  close;     //  Get  contact  form,  add  onsubmit  event  to  it   if  (form  =  $$('#contactform  form')[0])  {         $('name').focus();       //  Add  success/failure  events  to  form     form.set('send',  {       onSuccess:this.sendSuccess.bind(this),       onFailure:this.sendFailure.bind(this)     });         form.addEvent('submit',  function(){       //  You  could  perform  more  checks  here       form.send();       return  false;     });     }   //  Check  if  closewindow  exists.  If  not,  create  it   if  (  !  (close  =  $('closewindow')))  {
  45.   failed  :  function()  {     this.container.set('html',  'FAIL!');  

    },   sendSuccess  :  function()  {     $('contactform').set('html',  '<p>Huzzah!  The  form  was  sent!</p>');     setTimeout(this.close.bind(this),  1750);       },   sendFailure  :  function()  {     $('contactform').set('html',  '<p>FAIL!  Try  again  later.</p>');     setTimeout(this.close.bind(this),  1750);   },   close  :  function()  {     //  dispose  elements  so  we  can  re-­‐use  later     this.container.dispose();     this.overlay.dispose();     return  false;   }
  46. None
  47. Time for one more?

  48. None
  49. None
  50. None
  51. {exp:weblog:entries  weblog="extras"}   ...   {if  ex_type  ==  "Infographic"}  

        <div  class="extra  graph"  id="extra{count}">       <h2>{title}</h2>       {ex_text}       {exp:list_maker         class="graphdata"         id="graph_{entry_id}"}{ex_data}{/exp:list_maker}     </div>     {/if}     ... {/exp:weblog:entries}
  52. <?xml  version="1.0"  encoding="utf-­‐8"?> <pie> {exp:weblog:entries  weblog="extras"} <?php   $data  =<<<EOF

    {ex_data} EOF;   $data  =  explode("\n",trim($data));   foreach  ($data  AS  $row)  :     $slice  =  explode(':',$row);     echo  '<slice  title="'.trim($slice[0]).'">'.trim($slice[1]).'</slice>';   endforeach; ?> {/exp:weblog:entries} </pie>
  53. Questions?

  54. http://www.flickr.com/photos/goopymart/291244864/