<?php echo $content_for_layout; ?>
After executing the controller funcitons, the relavent view *.ctp file will be rendered where you have placed above code inside the layout page. If you consider blog example, after executing PostsController's view() action, view.ctp file will be rendered. This is the default behaviour of cake php. But, you may need more control when rendering view files in cake php than the above default behaviour. Sometime, you may need to load the relavent view file's contents into a spacific DIV tag in currently rendered page without refreshing the page. In this case, you may need AJAX support with cake php. I will explain how to do this with cake php. And also, I am going to explain how to get JSON response from cake php's controller function and update some contents of the page with javascript function. I am going to use jQuery support for this functionality. To have jQuery support for my cake php project, I include the fallowing in my laytout page.(This layout may be default.ctp or your own another layout page).
<?php echo $javascript->link('jquery-1.3.2');?>
The above line links 'jquery-1.3.2.js' file to my layout page.
Now, you we have jQuery support for our business. But not all. jQuery has sevaral UI supports. Next, we will start the real task. I am going to create the client side javascript function that makes AJAX request to cake php controller's action.
I am going to create Post data view function(Think about cake php blog example) with ajax support. Post title will be listed as links, and when user clicks on link, the relavent post information will display in a DIV tag somewhere in the same page.
<?php foreach($posts as $post): ?> <a href="#" onclick="viewPost(<?php echo $post['Post']['id'];?>)"> <?php echo $post['Post']['title'];?><br/> </a> <?php endforeach; ?>
$posts is a variable defined in a controller before rendering this page.
The above code shows how to create list of links using cake php. When click on each link, viewPost() function will be called and relavent post id will be passed into that function. The viewPost() function will take the responsibilities to make the AJAX request to cake php action and subsequently update the page contents.
The javascript code for the viewPost() function as fallows.
function viewPost(postId){ var data = "id="+ postId; $.ajax({ type: "post", // Request method: post, get url: "/cake/index.php/posts/view/", // URL to request data: data, // post data success: function(response) { document.getElementById("post-view").innerHTML = response; }, error:function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); return false; }
$.ajax() is a jquery function that suports to make AJAX request to the server. You have to specify the path to your cake php action for url option. "success" and "error" are tow callback functions suporting by $.ajax() function. "success" callback function will be fired with the succesfull response from the server. If some error occured at the server "error" callback function will be fired. The code for updating client side with successfull response should take place inside the "success" callback function.
The "success" callback function will be passed the contents of the response page if the server response type is 'text/html'. In this case, response will be the contents of /app/views/posts/view.ctp file. In this case the server response type will be 'text/html'. "success" callback function will receive the reponse data and set as the inner html of the DIV tag with id "post-view". You can do what ever with the response data. Keep in mind, this response data is just text or html. Using data option, we can pass some data into the server as http post data.
Next, we will explore the server side code for the view action in cake php controller. The code as fallows.
Next, we will explore the server side code for the view action in cake php controller. The code as fallows.
function view($id = null) { Configure::write('debug', 0); if($id == null){ $id = $_POST["id"]; } $this->pageTitle = 'View Post'; if($this->RequestHandler->isAjax()) { $post = $this->Post->findById($id); $this->set('post', $post); $this->layout = 'ajax'; $this->render('view'); } else { $post = $this->Post->findById($id); $this->set('post', $post); $this->layout = 'post_layout'; $this->render('view'); } }
This function supports for both behaviours. The cake php default behaviours and also this function responses for AJAX request. Function checks the request type for ajax or normal request and then proceed based on that. Cake php's RequestHandler component helps to check the request type.If the request is AJAX request, the layout is being changed to 'ajax' to support for a ajax response.
When the request is ajax, /app/views/posts/view.ctp file's content will be passed to the client as normal text/html. Then from the client side, "success" callback function will get this response and update the client page. If the request is normal request,/app/views/posts/view.ctp file will render in default cake php's behaviour, where you have placed <?php echo $content_for_layout; ?>.
When the request is ajax, /app/views/posts/view.ctp file's content will be passed to the client as normal text/html. Then from the client side, "success" callback function will get this response and update the client page. If the request is normal request,/app/views/posts/view.ctp file will render in default cake php's behaviour, where you have placed <?php echo $content_for_layout; ?>.
Next we will consider,how to get the response as JSON object from cake php's controller action. Some time you may need to get JSON object as the response from the php controller's action. With slight changes to above code, we can have a JSON response. The javascript function making the AJAX request as fallows.
function viewPost(postId){ var data = "id="+ postId; $.ajax({ type: "post", // Request method: post, get url: "/cake/index.php/posts/view/", // URL to request data: data, // Form variables dataType: "json", // Expected response type success: function(response) { var sb = []; sb[sb.length] = "Title :" + response.data.title + ""; sb[sb.length] = "Body :" + response.data.body; document.getElementById("post-view").innerHTML = sb.join(""); }, error:function (XMLHttpRequest, textStatus, errorThrown) { alert(textStatus); } }); return false; }
Note that, I have specified the dataType option as "json". This is important, if we want to get JSON response from the server. JSON object from the server will automatically converted into a javascript object. Then we can traverse the object and update the page with some dynamic html.
Next we will see the server side code, which makes the json response.
function view($id = null) { if($id == null){ $id = $_POST["id"]; } $post = $this->Post->findById($id); $this->set('post', $post); $this->pageTitle = 'View Post'; if($this->RequestHandler->isAjax()) { Configure::write('debug', 0); $post = $this->Post->findById($id); $this->layout = 'ajax'; $this->autoLayout = false; $this->autoRender = false; $this->header('Content-Type: application/json'); $data = array(); $result = array(); $data = array('title' => $post['Post']['title'], 'body' => $post['Post']['body']); $result['status'] = "success"; $result['data'] = $data; echo json_encode($result); return; } else { $this->layout = 'post_layout'; $this->render('view'); } }
This function also supports for both the behaviours, ie: cake php's default behaviour which renders /app/views/posts/view.ctp file after executing the action method. If the request is ajax request, it creates a JSON object and send it back to the browser as the response. PHP json_encode() function makes PHP array into JSON object. Note that, I have set change the layout to 'ajax' and autoRender to false. Content type should be set to 'application/json' for JSON response. Like this you can response any of data as JSON objects back to the browser. In the client side, use some javascript to create the dynamic html from these data. You can do nice ajax with JSON. Personally, I like JSON. I hope you too. Go ahead guys ...
Hi!
ReplyDeleteOn my site you can find AJAX Helper with jQuery.
http://www.cakephp.bee.pl/
Many functions are implemented and I put some examples on this site.
This solution works. AJAX Helper with jQuery is useless.
ReplyDeleteReally helpful post.
ReplyDeletethanks for sharing.
Really Helpful dude....
ReplyDeleteRequest you to please update this with latest version so that we new comer can benefit from it fully.
please help me i am stucking in same problem
ReplyDeleteThanks a lot very much for the high quality and results-oriented help. I won’t think twice to endorse your blog post to anybody who wants and needs support about this area.
ReplyDeletedigital marketing training in tambaram
digital marketing training in annanagar
digital marketing training in marathahalli
digital marketing training in rajajinagar
Digital Marketing online training
full stack developer training in pune
Well researched article and I appreciate this. The blog is subscribed and will see new topics soon.
ReplyDeletepython training institute in chennai
python training in Bangalore
python training in pune
python online training
Your very own commitment to getting the message throughout came to be rather powerful and have consistently enabled employees just like me to arrive at their desired goals.
ReplyDeleteData science training in tambaram | Data Science training in anna nagar
Data Science training in chennai | Data science training in Bangalore
Data Science training in marathahalli | Data Science training in btm
Thanks for the informative article. This is one of the best resources I have found in quite some time. Nicely written and great info. I really cannot thank you enough for sharing.
ReplyDeleteangularjs-Training in tambaram
angularjs-Training in sholinganallur
angularjs-Training in velachery
angularjs Training in bangalore
angularjs Training in bangalore
Really I enjoy your blog with an effective and useful information. Very nice post with loads of information. Thanks for sharing with us.
ReplyDeleteSelenium Training in Chennai
selenium Classes in chennai
iOS Training in Chennai
Digital Marketing Training in Chennai
SEO Course in Adyar
SEO Course in Velachery
We are a group of volunteers and starting a new initiative in a community. Your blog provided us valuable information to work on.You have done a marvellous job!
ReplyDeleteDevops Training in Chennai | Devops Training Institute in Chennai
I have to voice my passion for your kindness giving support to those people that should have guidance on this important matter.
ReplyDeleteBest PHP Training Institute in Chennai|PHP Course in chennai
Best .Net Training Institute in Chennai
Dotnet Training in Chennai
Dotnet Training in Chennai
Really very happy to say, your post is very interesting to read. I never stop myself to say something about it. You’re doing a great job. Keep it up…
ReplyDeleteLearn Best Microstrategy Training in Bangalore from Experts. Softgen Infotech offers the Best RPA Training in Bangalore.100% Placement Assistance, Live Classroom Sessions, Only Technical Profiles, 24x7 Lab Infrastructure Support.
very useful post...
ReplyDeleteinplant training in chennai
inplant training in chennai
inplant training in chennai for it
Australia hosting
mexico web hosting
moldova web hosting
albania web hosting
andorra hosting
australia web hosting
denmark web hosting
nice....
ReplyDeleteinplant training in chennai
inplant training in chennai for it
panama web hosting
syria hosting
services hosting
afghanistan shared web hosting
andorra web hosting
belarus web hosting
brunei darussalam hosting
inplant training in chennai
I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. Thanks...
ReplyDeleteDigital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery
excellent one..nice,creative..Thanks for the Giving the Good content to making valuable more. Appreciating all of your efforts to giving such an informative Blogs.
ReplyDeleteBEST ANGULAR JS TRAINING IN CHENNAI WITH PLACEMENT
https://www.acte.in/angular-js-training-in-chennai
https://www.acte.in/angular-js-training-in-annanagar
https://www.acte.in/angular-js-training-in-omr
https://www.acte.in/angular-js-training-in-porur
https://www.acte.in/angular-js-training-in-tambaram
https://www.acte.in/angular-js-training-in-velachery
This is really very good article about java.
ReplyDeleteAngularJS training in chennai | AngularJS training in anna nagar | AngularJS training in omr | AngularJS training in porur | AngularJS training in tambaram | AngularJS training in velachery
"Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
ReplyDeleteDigital Marketing Training Course in Chennai | Digital Marketing Training Course in Anna Nagar | Digital Marketing Training Course in OMR | Digital Marketing Training Course in Porur | Digital Marketing Training Course in Tambaram | Digital Marketing Training Course in Velachery
"
Really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot. it is really explainable very well and i got more information from your blog.
ReplyDeletepython training in chennai
python online training in chennai
python training in bangalore
python training in hyderabad
python online training
python flask training
python flask online training
python training in coimbatore
I would like to thank you for the efforts you have made in writing this article. I am hoping the same best work from you in the future as well. Thanks...
ReplyDeleteWeb design Training in Chennai
Web design Training in Velachery
Web design Training in Tambaram
Web design Training in Porur
Web design Training in Omr
Web design Training in Annanagar
Antalya
ReplyDeleteAntep
Burdur
Sakarya
istanbul
2KMRTQ
Batman
ReplyDeleteArdahan
Adıyaman
Antalya
Giresun
NC13OU
Antalya
ReplyDeleteAntep
Burdur
Sakarya
istanbul
W7İP0G
goruntulu show
ReplyDeleteücretli
BK8
ankara parça eşya taşıma
ReplyDeletetakipçi satın al
antalya rent a car
antalya rent a car
ankara parça eşya taşıma
TAFM
adana evden eve nakliyat
ReplyDeletebolu evden eve nakliyat
diyarbakır evden eve nakliyat
sinop evden eve nakliyat
kilis evden eve nakliyat
1TNKL1
4A40C
ReplyDeleteArdahan Lojistik
Sinop Lojistik
Bursa Evden Eve Nakliyat
Kilis Parça Eşya Taşıma
Samsun Evden Eve Nakliyat
A05F4
ReplyDeleteMaraş Şehir İçi Nakliyat
Kastamonu Şehirler Arası Nakliyat
Çanakkale Parça Eşya Taşıma
Sinop Lojistik
Sakarya Evden Eve Nakliyat
Çerkezköy Marangoz
Bursa Şehirler Arası Nakliyat
Hakkari Lojistik
Rize Şehir İçi Nakliyat
2F98B
ReplyDeleteKütahya Şehirler Arası Nakliyat
Eskişehir Parça Eşya Taşıma
Çankaya Boya Ustası
Çerkezköy Oto Elektrik
Yozgat Evden Eve Nakliyat
Uşak Şehirler Arası Nakliyat
Bitmart Güvenilir mi
Ankara Lojistik
Denizli Şehir İçi Nakliyat
943F6
ReplyDeleteBalıkesir Lojistik
Bartın Şehirler Arası Nakliyat
Yalova Şehirler Arası Nakliyat
Çerkezköy Boya Ustası
Malatya Lojistik
Çerkezköy Yol Yardım
Bitget Güvenilir mi
Silivri Fayans Ustası
Manisa Lojistik
B05C6
ReplyDeleteAmasya Evden Eve Nakliyat
Bartın Şehirler Arası Nakliyat
Yenimahalle Fayans Ustası
Binance Güvenilir mi
Urfa Lojistik
Karapürçek Fayans Ustası
Urfa Şehirler Arası Nakliyat
Tekirdağ Şehir İçi Nakliyat
Eryaman Fayans Ustası
6F361
ReplyDeletecanlı ücretsiz sohbet
eskişehir canlı sohbet
kadınlarla rastgele sohbet
ığdır kadınlarla ücretsiz sohbet
bolu görüntülü sohbet kızlarla
sakarya görüntülü sohbet
niğde sohbet
kilis sohbet sitesi
osmaniye tamamen ücretsiz sohbet siteleri
B04E8
ReplyDeletedenizli yabancı görüntülü sohbet uygulamaları
yozgat kadınlarla sohbet
Trabzon Canlı Ücretsiz Sohbet
adana rastgele görüntülü sohbet
görüntülü sohbet kadınlarla
Mardin Görüntülü Canlı Sohbet
sesli sohbet
Erzurum Yabancı Sohbet
kocaeli sesli mobil sohbet
48835
ReplyDeleteTwitter Trend Topic Satın Al
Kripto Para Kazanma Siteleri
Görüntülü Sohbet
Binance Referans Kodu
Kripto Para Nasıl Kazılır
Alyattes Coin Hangi Borsada
Facebook Sayfa Beğeni Hilesi
Likee App Takipçi Hilesi
Binance Hesap Açma
I really liked your blog article. Great Thanks.
ReplyDeleteBest Mean Stack Training from South Africa
VUE JS Online Training Coaching
Express JS Online Training from USA, Uk, Australia, UAE, Canada
Puppet Training from UK
Chef Online Course from India
Best Maven Training
Best Ansible Training from Hyderabad
Respect and I have a super give: Where To Buy Houses That Need Renovation house renovation tips
ReplyDelete