Download - CakePHP and AJAX

Transcript
Page 1: CakePHP and AJAX

CakeFestConference2014-MarkScherer(@dereuromark)

Page 2: CakePHP and AJAX

UsingCakePHPfor6+years(startingwith1.2)CoreDevelopersince2+yearsActivebloggeraboutCakePHPissuesandsolutions

Germany(Berlin)PassionatePHPandOpenSourceDeveloper

Page 3: CakePHP and AJAX

WhatisAJAXWhentouseitBasicsUsingGETUsingPOSTMoreexamplesTips

Page 4: CakePHP and AJAX
Page 5: CakePHP and AJAX

Loadthewholepageonce.

Thenfetchonlypartsortinysnippetsofupdatesviafollow-uprequests.

Onlyneedsafractionoftheresource/bandwith.

Page 6: CakePHP and AJAX

DataexchangewithoutchangingpositionInlineeditingRealtimevalidationNativelookandfeelPre-fetchingDatalookups...

Page 7: CakePHP and AJAX

SEO/CrawlingBrowserHistoryBookmarkingNetworkissuesPollingSameOriginPolicy

Page 8: CakePHP and AJAX

GETrequestsshouldbeusedonlytoretrievedata

Page 9: CakePHP and AJAX

/controller/actiontext/html

/controller/action.jsonapplication/json

URLshouldmatchtheexpectedformat

Page 10: CakePHP and AJAX

//Config/routes.php

Router::parseExtensions();Router::setExtensions(array('json','xml','csv','rss','pdf'));

//AppController.php

public$components=array('RequestHandler');

Page 11: CakePHP and AJAX

if($this->request->is(array('ajax'))){}

$this->request->allowMethod('ajax');

Page 12: CakePHP and AJAX

/***AJAXactiontogetfavorites**@returnstring*/publicfunctionfavorites(){$this->autoRender=false;//Wedon'trenderaviewinthisexample$this->request->allowMethod(array('ajax'));//NodirectaccessviabrowserURL$data=array('content'=>...,'error'=>'',);$this->response->body(json_encode($data));}

GET/controller_name/favorites.json

Page 13: CakePHP and AJAX

/***AJAXactiontogetfavorites**@returnvoid*/publicfunctionfavorites(){$this->request->allowMethod(array('ajax'));//NodirectaccessviabrowserURL$data=array('content'=>...,'error'=>'',);$this->set(compact('data'));//Pass$datatotheview$this->set('_serialize','data');//LettheJsonViewclassknowwhatvariabletouse}

Page 14: CakePHP and AJAX

<p><buttonclass="ajax-button"data-url="<?phpecho$this->Html->url(array('action'=>'favorites','ext'=>'json'))?>">Clickme</button></p>

<p>Result:<spanid="target"></span></p>

Page 15: CakePHP and AJAX

$(function(){$('.ajax-button').click(function(e){vartargeturl=$(this).data('url');$.ajax({type:"get",url:targeturl,beforeSend:function(xhr){xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');},success:function(res){if(res.error!=''){alert(res.error);}else{$('#target').html(res.content);}},error:function(e){alert("FehlerbeiderAnfrage!");console.log(e);}});});});

Page 16: CakePHP and AJAX

$_ENV['HTTP_X_REQUESTED_WITH']='XMLHttpRequest';$url=Router::url(array('controller'=>'controller_name','action'=>'favorites','ext'=>'json','?'=>array('id'=>2)));$options=array('return'=>'vars');$result=$this->testAction($url,$options);...

Makessure$this->request->allowMethod(array('ajax'));passes

Page 17: CakePHP and AJAX

...data:{'one':$('#one').val(),'two':$('#two').val()},...

$one=$this->request->data('one');$two=$this->request->data('two');

Page 18: CakePHP and AJAX

$_ENV['HTTP_X_REQUESTED_WITH']='XMLHttpRequest';$url=Router::url(array('controller'=>'controller_name','action'=>'favorites','ext'=>'json','?'=>array('id'=>2)));$options=array('data'=>array(...),'method'=>'post''return'=>'vars');$result=$this->testAction($url,$options);...

'data'arraywithmethodtype'post'

Page 19: CakePHP and AJAX

ToggleAutocompleteChaineddropdownsPagination

Page 20: CakePHP and AJAX

//AppController.php-e.g.inbeforeRender()

if($this->request->is('ajax')){$this->response->disableCache();}

Page 21: CakePHP and AJAX

Questions?

Page 22: CakePHP and AJAX

http://book.cakephp.orghttps://github.com/dereuromark/cakefest2014-apphttp://sandbox.dereuromark.de/sandbox/ajax_exampleshttp://sandbox.dereuromark.de/sandbox/jquery_examples/autocompletehttp://www.dereuromark.de/2014/01/09/ajax-and-cakephp/https://github.com/dereuromark/tools