SlideShare a Scribd company logo
CakeFest	Conference	2014	-	Mark	Scherer	(@dereuromark)
Using	CakePHP	for	6+	years	(starting	with	1.2)
Core	Developer	since	2+	years
Active	blogger	about	CakePHP	issues	and	solutions
Germany	(Berlin)
Passionate	PHP	and	Open	Source	Developer
What	is	AJAX
When	to	use	it
Basics
Using	GET
Using	POST
More	examples
Tips
Load	the	whole	page	once.
Then	fetch	only	parts	or	tiny	snippets	of
updates	via	follow-up	requests.
Only	needs	a	fraction	of	the
resource/bandwith.
Data	exchange	without	changing	position
Inline	editing
Real	time	validation
Native	look	and	feel
Pre-fetching
Data	lookups
...
SEO	/	Crawling
Browser	History
Bookmarking
Network	issues
Polling
Same	Origin	Policy
GET	requests	should	be	used	only	to
retrieve	data
/controller/action
				text/html
/controller/action.json
				application/json
URL	should	match	the	expected	format
//	Config/routes.php
Router::parseExtensions();
Router::setExtensions(array('json',	'xml',	'csv',	'rss',	'pdf'));
//	AppController.php
public	$components	=	array('RequestHandler');
if	($this->request->is(array('ajax')))	{}
$this->request->allowMethod('ajax');
/**
	*	AJAX	action	to	get	favorites
	*
	*	@return	string
	*/
public	function	favorites()	{
				$this->autoRender	=	false;	//	We	don't	render	a	view	in	this	example
				$this->request->allowMethod(array('ajax'));	//	No	direct	access	via	browser	URL
	
				$data	=	array(
								'content'	=>	...,
								'error'	=>	'',
				);
				$this->response->body(json_encode($data));
}
GET	/controller_name/favorites.json
/**
	*	AJAX	action	to	get	favorites
	*
	*	@return	void
	*/
public	function	favorites()	{
				$this->request->allowMethod(array('ajax'));	//	No	direct	access	via	browser	URL
	
				$data	=	array(
								'content'	=>	...,
								'error'	=>	'',
				);
				$this->set(compact('data'));	//	Pass	$data	to	the	view
				$this->set('_serialize',	'data');	//	Let	the	JsonView	class	know	what	variable	to	use
}
<p>
<button	
				class="ajax-button"	
				data-url="<?php	echo	$this->Html->url(array('action'	=>	'favorites',	'ext'	=>	'json'))?>">
Click	me
</button>
</p>
<p>
Result:	<span	id="target"></span>
</p>
$(function()	{
				$('.ajax-button').click(function(e)	{
								var	targeturl	=	$(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("Fehler	bei	der	Anfrage!");
																console.log(e);
												}
								});
				});
});
$_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);
...
Makes	sure	$this->request->allowMethod(array('ajax'));	passes
...
data:	{'one'	:	$('#one').val(),	'two'	:	$('#two').val()},
...
$one	=	$this->request->data('one');
$two	=	$this->request->data('two');
$_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'	array	with	method	type	'post'
Toggle
Autocomplete
Chained	dropdowns
Pagination
//	AppController.php	-	e.g.	in	beforeRender()
if	($this->request->is('ajax'))	{
				$this->response->disableCache();
}
Questions?
http://book.cakephp.org
https://github.com/dereuromark/cakefest2014-app
http://sandbox.dereuromark.de/sandbox/ajax_examples
http://sandbox.dereuromark.de/sandbox/jquery_examples/
		autocomplete
http://www.dereuromark.de/2014/01/09/ajax-and-
cakephp/
https://github.com/dereuromark/tools

More Related Content

What's hot

Tools of the CPAN Ninja
Tools of the CPAN NinjaTools of the CPAN Ninja
Tools of the CPAN Ninja
Aran Deltac
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Matthew Farwell
 
Sauce Labs Beta Program Overview
Sauce Labs Beta Program OverviewSauce Labs Beta Program Overview
Sauce Labs Beta Program Overview
Al Sargent
 

What's hot (20)

Django, What is it, Why is it cool?
Django, What is it, Why is it cool?Django, What is it, Why is it cool?
Django, What is it, Why is it cool?
 
Behaviour Driven Development con Behat & Drupal
Behaviour Driven Development con Behat & DrupalBehaviour Driven Development con Behat & Drupal
Behaviour Driven Development con Behat & Drupal
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Presentation laravel 5 4
Presentation laravel 5 4Presentation laravel 5 4
Presentation laravel 5 4
 
Play with Alfresco ADF 2.0.0 Angular
Play with Alfresco ADF 2.0.0 AngularPlay with Alfresco ADF 2.0.0 Angular
Play with Alfresco ADF 2.0.0 Angular
 
Laravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello ProductionLaravel Forge: Hello World to Hello Production
Laravel Forge: Hello World to Hello Production
 
Intro to CakePHP 1.3
Intro to CakePHP 1.3Intro to CakePHP 1.3
Intro to CakePHP 1.3
 
40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently40+ tips to use Postman more efficiently
40+ tips to use Postman more efficiently
 
Tools of the CPAN Ninja
Tools of the CPAN NinjaTools of the CPAN Ninja
Tools of the CPAN Ninja
 
Django app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh AgarwalDjango app deployment in Azure By Saurabh Agarwal
Django app deployment in Azure By Saurabh Agarwal
 
Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8Installing php 7.4 Nginx Laravel 7.x on Centos 8
Installing php 7.4 Nginx Laravel 7.x on Centos 8
 
php[world] 2015 Laravel 5.1: From Homestead to the Cloud
php[world] 2015 Laravel 5.1: From Homestead to the Cloudphp[world] 2015 Laravel 5.1: From Homestead to the Cloud
php[world] 2015 Laravel 5.1: From Homestead to the Cloud
 
CPAN Dependency Heaven
CPAN Dependency HeavenCPAN Dependency Heaven
CPAN Dependency Heaven
 
Django
DjangoDjango
Django
 
Nexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and SprayNexthink Library - replacing a ruby on rails application with Scala and Spray
Nexthink Library - replacing a ruby on rails application with Scala and Spray
 
Laravel 5.4
Laravel 5.4 Laravel 5.4
Laravel 5.4
 
Web Application Development using MVC Framework Kohana
Web Application Development using MVC Framework KohanaWeb Application Development using MVC Framework Kohana
Web Application Development using MVC Framework Kohana
 
Why Laravel?
Why Laravel?Why Laravel?
Why Laravel?
 
Sauce Labs Beta Program Overview
Sauce Labs Beta Program OverviewSauce Labs Beta Program Overview
Sauce Labs Beta Program Overview
 
10 Laravel packages everyone should know
10 Laravel packages everyone should know10 Laravel packages everyone should know
10 Laravel packages everyone should know
 

Viewers also liked

Questionnaire analysis stephen
Questionnaire analysis stephenQuestionnaire analysis stephen
Questionnaire analysis stephen
SHubbard1
 
Hakaworks proposal russia jul13
Hakaworks proposal russia jul13Hakaworks proposal russia jul13
Hakaworks proposal russia jul13
Kirill Ustinov
 
Socializacijos programa „Bildukai 2010“
Socializacijos programa „Bildukai 2010“Socializacijos programa „Bildukai 2010“
Socializacijos programa „Bildukai 2010“
Vidmantas Budrys
 
Prezentacja sms wroclaw
Prezentacja sms wroclawPrezentacja sms wroclaw
Prezentacja sms wroclaw
Scubaru
 
Обзор работы паевых фондов 31 октября - 7 ноября
Обзор работы паевых фондов 31 октября - 7 ноябряОбзор работы паевых фондов 31 октября - 7 ноября
Обзор работы паевых фондов 31 октября - 7 ноября
Sergey Manvelov
 
2 класс. lesson 39. волшебная шляпа
2 класс. lesson 39. волшебная шляпа2 класс. lesson 39. волшебная шляпа
2 класс. lesson 39. волшебная шляпа
shpinat
 

Viewers also liked (20)

CakePHP mistakes made
CakePHP mistakes madeCakePHP mistakes made
CakePHP mistakes made
 
Recursive in CakePHP
Recursive in CakePHPRecursive in CakePHP
Recursive in CakePHP
 
Customize CakePHP bake
Customize CakePHP bakeCustomize CakePHP bake
Customize CakePHP bake
 
CakePHP Community Keynote 2014
CakePHP Community Keynote 2014CakePHP Community Keynote 2014
CakePHP Community Keynote 2014
 
PHPUnit with CakePHP and Yii
PHPUnit with CakePHP and YiiPHPUnit with CakePHP and Yii
PHPUnit with CakePHP and Yii
 
Top 50 Interview Questions and Answers in CakePHP
Top 50 Interview Questions and Answers in CakePHPTop 50 Interview Questions and Answers in CakePHP
Top 50 Interview Questions and Answers in CakePHP
 
Agile database access with CakePHP 3
Agile database access with CakePHP 3Agile database access with CakePHP 3
Agile database access with CakePHP 3
 
Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3Advanced Querying with CakePHP 3
Advanced Querying with CakePHP 3
 
Katalog
KatalogKatalog
Katalog
 
Questionnaire analysis stephen
Questionnaire analysis stephenQuestionnaire analysis stephen
Questionnaire analysis stephen
 
Hakaworks proposal russia jul13
Hakaworks proposal russia jul13Hakaworks proposal russia jul13
Hakaworks proposal russia jul13
 
Socializacijos programa „Bildukai 2010“
Socializacijos programa „Bildukai 2010“Socializacijos programa „Bildukai 2010“
Socializacijos programa „Bildukai 2010“
 
Media ppt
Media pptMedia ppt
Media ppt
 
Prezentacja sms wroclaw
Prezentacja sms wroclawPrezentacja sms wroclaw
Prezentacja sms wroclaw
 
iPad 2 accessibility
iPad 2 accessibilityiPad 2 accessibility
iPad 2 accessibility
 
Обзор работы паевых фондов 31 октября - 7 ноября
Обзор работы паевых фондов 31 октября - 7 ноябряОбзор работы паевых фондов 31 октября - 7 ноября
Обзор работы паевых фондов 31 октября - 7 ноября
 
인류 진보 강화 계획
인류 진보 강화 계획인류 진보 강화 계획
인류 진보 강화 계획
 
Topik 1.0
Topik 1.0Topik 1.0
Topik 1.0
 
2 класс. lesson 39. волшебная шляпа
2 класс. lesson 39. волшебная шляпа2 класс. lesson 39. волшебная шляпа
2 класс. lesson 39. волшебная шляпа
 
Introduction to libel
Introduction to libel Introduction to libel
Introduction to libel
 

Similar to CakePHP and AJAX

Optimizing CakePHP 2.x Apps
Optimizing CakePHP 2.x AppsOptimizing CakePHP 2.x Apps
Optimizing CakePHP 2.x Apps
Juan Basso
 
03 form-data
03 form-data03 form-data
03 form-data
snopteck
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
hazzaz
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
WalaSidhom1
 
ODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data Management
ODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data ManagementODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data Management
ODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data Management
Francisco Amores
 
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Nguyen Duc Phu
 
PHP Continuous Data Processing
PHP Continuous Data ProcessingPHP Continuous Data Processing
PHP Continuous Data Processing
Michael Peacock
 
Cakefest 2010: API Development
Cakefest 2010: API DevelopmentCakefest 2010: API Development
Cakefest 2010: API Development
Andrew Curioso
 
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
lanslote
 

Similar to CakePHP and AJAX (20)

Optimizing CakePHP 2.x Apps
Optimizing CakePHP 2.x AppsOptimizing CakePHP 2.x Apps
Optimizing CakePHP 2.x Apps
 
03 form-data
03 form-data03 form-data
03 form-data
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
Web api
Web apiWeb api
Web api
 
nguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-servicenguyenhainhathuy-building-restful-web-service
nguyenhainhathuy-building-restful-web-service
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
 
SPFx Webinar Loading SharePoint data in a SPFx Webpart
SPFx Webinar Loading SharePoint data in a SPFx WebpartSPFx Webinar Loading SharePoint data in a SPFx Webpart
SPFx Webinar Loading SharePoint data in a SPFx Webpart
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Oracle APEX URLs Untangled & SEOptimized
Oracle APEX URLs Untangled & SEOptimizedOracle APEX URLs Untangled & SEOptimized
Oracle APEX URLs Untangled & SEOptimized
 
HTTP Basics Demo
HTTP Basics DemoHTTP Basics Demo
HTTP Basics Demo
 
ODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data Management
ODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data ManagementODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data Management
ODTUG KSCOPE 2018 - REST APIs for FDMEE and Cloud Data Management
 
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
Hanoi php day 2008 - 05. nguyen hai nhat huy - building-restful-web-service-w...
 
What's new in Rails 4
What's new in Rails 4What's new in Rails 4
What's new in Rails 4
 
PHP Continuous Data Processing
PHP Continuous Data ProcessingPHP Continuous Data Processing
PHP Continuous Data Processing
 
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful  Protocol BuffersJavaOne 2009 - TS-5276 - RESTful  Protocol Buffers
JavaOne 2009 - TS-5276 - RESTful Protocol Buffers
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 
Cakefest 2010: API Development
Cakefest 2010: API DevelopmentCakefest 2010: API Development
Cakefest 2010: API Development
 
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
[SharePoint Korea Conference 2013 / 강율구] Sharepoint 스마트하게 개발하기
 
Cakephp
CakephpCakephp
Cakephp
 

Recently uploaded

Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
mbmh111980
 

Recently uploaded (20)

Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
Paketo Buildpacks : la meilleure façon de construire des images OCI? DevopsDa...
 
Agnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in KrakówAgnieszka Andrzejewska - BIM School Course in Kraków
Agnieszka Andrzejewska - BIM School Course in Kraków
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
Crafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM IntegrationCrafting the Perfect Measurement Sheet with PLM Integration
Crafting the Perfect Measurement Sheet with PLM Integration
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Designing for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web ServicesDesigning for Privacy in Amazon Web Services
Designing for Privacy in Amazon Web Services
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdfMastering Windows 7 A Comprehensive Guide for Power Users .pdf
Mastering Windows 7 A Comprehensive Guide for Power Users .pdf
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAGAI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
AI/ML Infra Meetup | Reducing Prefill for LLM Serving in RAG
 
Advanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should KnowAdvanced Flow Concepts Every Developer Should Know
Advanced Flow Concepts Every Developer Should Know
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 

CakePHP and AJAX