In CakePHP 2.x, i use this path to show results to visitors example.com/my/showResults *getSomeResults* function makes some Twitter API requests which lasts generally 5-25 seconds.
I need to put a "loading div" into my view. But i couldn't decide the structure.
The examples i found by google shows, when user clicks a button, an AJAX request is made and results are shown in that div.
But in my case, when the page is loaded that request will be done asynchronously, when results are available, they will be shown in another div.
Regarding to my file structure below, where should i put AJAX request? Should i remove lines in showResults method and run another action when AJAX request will succeed?
I would be happy if you can recommend a structure for, show results when AJAX request is succeed in CakePHP 2 way. Thank you
// appcontroller.php
class AppController extends Controller {
function getSomeResults() {
// make some http requests to twitter API
}
}
// mycontroller.php
class MyController extends AppController {
public function showResults() {
$data=$this->getSomeResults();
$this->set('data', $data);
$this->render('myelement');
}
}
// myelement.ctp
<div id="before">
Please wait loading..
</div>
<div id="results" style="display: none">
<?php echo $data ?>
</div>
// myscript.js
$(document).ready(function() {
$("#results").hide();
setTimeout('$("#results").show();',8000);
}
It looks to me, like you are grabbing the web service and then handing off the data through cakephp. Meaning it does not look like you are using ajax at all.
Since you appear to be using jquery already I would recommend that you connect to twitter using jquery's ajax method [http://api.jquery.com/jQuery.ajax/]. So not only would you remove showResults(), but you would also remove getSomeResults(). If you needed this info to be refreshed you could set this ajax call into a function and call it on a regular interval.
Unless you had the div for loading at the top of the page, you could use jquery to change the results div from now loading to the data.
Just my 2 cents.