Searching data using Ajax in CakePHP - ajax

I am using CakePHP 2.3.6. In one of my projects, I have to implement the Searching feture, using AJAX. Normally, this is working, but I want that the page won't reload, the result table will be immediately updated with the data.
This is the Controller code:
public function searchData(){
$this->set(............);
$this->set(............);
$this->set(............);
if($this->request->is('post')){
$this->layout='ajax';
$this->autoRender=false;
if(!empty($data)){
$data=$this->request->data;
// Generating options
.
.
.
$result=$this->ModelName->find('all',$options);// "$options" is generated options
if(!empty($result)){
$this->set(compact($result));
$this->set('_serialize',array('result'));
print_r(json_encode($result));
$this->Session->setFlash("Searching Applicants Successful");
$this->set('result',$result);
}else
$this->Session->setFlash("No data found");
}else
$this->Session->setFlash("You didn't give any info to search for");
}
}
My View file(search_data.ctp) :
<h3>Search Result</h3>
<?php
echo $this->form->create();
echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
echo $this->Form->submit('Search');
echo $this->Form->end();
<div id="searchResult">
<?php if(!empty($result)){?>
<table class="table table-striped table-bordered table-hover">
<thead>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
<th>Field 4</th>
</thead>
<tbody>
<?php foreach($result as $applicant){?>
<tr>
<td><?php echo $result['ModelName']['field1'];?></td>
<td><?php echo $result['ModelName']['field2'];?></td>
<td><?php echo $result['ModelName']['field3'];?></td>
<td><?php echo $result['ModelName']['field4'];?></td>
</tr>
<?php }?>
</tbody>
</table>
<?php
}else
echo "No data found";
?>
</div>
Here, what I want is, when I submit the form, the "result" div will immediately appear, with the result data, organized in the table. I want to use Ajax here, so that users will get the result immediately, it'll improve the performance and user experience.
I've seen some youtube videos, where they load another page with the result, and shows that page in a div (it is called "success" div most of the time :) ), using Ajax. I can do it. But, I just want to do everything in 1 page, I don't want to use 2 pages to do it.
I tried this for ajax request and update my "result" div(in my search_data.ctp file) :
$this->Js->get('.search-form')->event('submit',$this->Js->request(array('controller'=>'cntrlr_name','action'=>'searchData'),array('async'=>true,'update'=>'#searchResult')));
And when I run the page, this is the output :
[{"Applicant":{"id":"3","name":"Name 2","email":"ssaha.316#gmail.com","mobile":"9082730572","contact_phone":"3465360980","office_phone":"2437845693","correspondence_address":"Correspondence Address 2","permanent_address":"Permanent Address 2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"},"ApplicantAcademicQualification":[{"id":"2","applicant_id":"3","level":"Bachelor(Pass)","degree_title":"B.A.","passing_year":"1999","institution":"Institution 2","result":"4.2","major":"Bengali Literature","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantEmploymentHistory":[{"id":"2","applicant_id":"3","employer":"Employer 2","position_held":"Position 2","industry":"Industry 2","department":"Department 2","major_responsibilities":"Responsibility 2","job_location":"Local","key_achievement":"Achievement 2","served_from":"1999-08-15","served_till":"2010-02-12","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantOther":[{"id":"2","applicant_id":"3","academic_activities":"Academic Activities 2","non_academic_activities":"Non Academic Activities 2","main_reason_for_applying":"Reason 2","worked_before":"0","last_position":"","work_location_constraint":"1","ready_to_join_on":"2008-08-14","expected_salary":"30k+","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantProfessionalQualification":[{"id":"2","applicant_id":"3","name_of_certificate":"Certificate 2","institute":"Institute 2","from":"2002-10-17","to":"2007-10-12","location":"Local Ins.","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}],"ApplicantTraining":[{"id":"2","applicant_id":"3","title":"Title 2","institute":"Institute 2","training_year":"1995","location":"In Company","created":"2014-05-31 18:22:17","modified":"2014-05-31 18:22:17"}]},{"Applicant":{"id":"2","name":"Name 1","email":"user1#email.com","mobile":"715414918934","contact_phone":"2357295090","office_phone":"083656987398","correspondence_address":"Address 1_1","permanent_address":"Address 1_2","preferred_work_areas":"Field 1, Field 2, Field 3","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"},"ApplicantAcademicQualification":[{"id":"1","applicant_id":"2","level":"Secondary","degree_title":"S.S.C","passing_year":"2009","institution":"Institute 1","result":"4","major":"Science","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantEmploymentHistory":[{"id":"1","applicant_id":"2","employer":"Employer 1","position_held":"Position 1","industry":"Industry 1","department":"Department 1","major_responsibilities":"Responsibilities 1","job_location":"Local","key_achievement":"Achievements 1","served_from":"2005-03-12","served_till":"2007-11-26","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantOther":[{"id":"1","applicant_id":"2","academic_activities":"Academic Activities 1","non_academic_activities":"Non Academic Activities 1","main_reason_for_applying":"Reason 1","worked_before":"1","last_position":"Last Position 1","work_location_constraint":"1","ready_to_join_on":"2008-07-10","expected_salary":"20k-25k","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantProfessionalQualification":[{"id":"1","applicant_id":"2","name_of_certificate":"Certificate 1","institute":"Institute 1","from":"2011-10-11","to":"2012-09-11","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}],"ApplicantTraining":[{"id":"1","applicant_id":"2","title":"Title 1","institute":"Institute 1","training_year":"2013","location":"Local Ins.","created":"2014-05-18 16:48:08","modified":"2014-05-18 17:20:12"}]}]
Is it possible ? How can I do it ? Please help me.
Thanks.

update your function searchData:
public function searchData(){
//just empty for showing the form only
}
add ajax function:
public function ajax_search(){
$this->layout="ajax";
$result = array();
$field1 = $_POST["field1"];
$field2 = $_POST["field2"];
$field3 = $_POST["field3"];
$field4 = $_POST["field4"];
if( $field1 && $field2 && $field3 && $field4 ){ //change this depending on your queries
$data=$this->request->data;
// Generating options
.
.
.
$result=$this->ModelName->find('all',$options);// "$options" is generated option
}
$this->set("result", $result);
}
add view ajax_search.ctp:
<?php if($result):?>
<table class="table table-striped table-bordered table-hover">
<thead>
<th>Field 1</th>
<th>Field 2</th>
<th>Field 3</th>
<th>Field 4</th>
</thead>
<tbody>
<?php foreach($result as $applicant){?>
<tr>
<td><?php echo $result['ModelName']['field1'];?></td>
<td><?php echo $result['ModelName']['field2'];?></td>
<td><?php echo $result['ModelName']['field3'];?></td>
<td><?php echo $result['ModelName']['field4'];?></td>
</tr>
<?php }?>
</tbody>
</table>
<?php else:?>
No results.
<?php endif;?>
update you searchData.ctp:
<h3>Search Result</h3>
<?php
echo $this->Form->create("Search",array("default"=>false, "id"=>"SearchForm"));
echo $this->Form->input('field1',array('type'=>'text,'div'=>false));
echo $this->Form->input('field2',array('type'=>'text,'div'=>false));
echo $this->Form->input('field3',array('type'=>'text,'div'=>false));
echo $this->Form->input('field4',array('type'=>'text,'div'=>false));
echo $this->Form->submit('Search');
echo $this->Form->end();
<div class="result">
;?>
<script type="text/javascript">
$(document).on('submit','#SearchForm',function(){
$.ajax({
type: "POST",
data:{
field1:$("#SearchField1").val, // the ids of your input or you can modify these if you have assigned ids to the input
field2:$("#SearchField2").val,
field3:$("#SearchField3").val,
field4:$("#SearchField4").val
},
beforeSend: function(){
$("#result").html("loading...");
}
url: "<?php echo $this->base;?>/{insert your controller name here}/ajax_search/",
success:function(data) {
$("#result").html(data);
}
});
});
</script>

Here are the steps:
Your search method returns data as JSON.
Then on your page loop data in jquery template.
Here is an example of how to use jQuery templates, and here it's documentation
Here is another approach
UPDATE
simple return json results from your search method:
public function searchData(){
$this -> layout = 'ajax';
$this -> autoRender = false;
if($this->request->is('post')){
if(!empty($data)){
$data=$this->request->data;
// Generating options
...
$result = $this->ModelName->find('all',$options);// "$options" is generated options
$this -> set(compact($result));
$this -> set('_serialize',array('result'));
echo json_encode($result);
}
}
}
Use and loop JSON results data

Related

Google AdSense API Refresh Token not working

From here:
Google AdSense API asking for log in each time
I tried and this worked the first time, but the next day, the script ran and got an error:
Uncaught exception 'Google_Auth_Exception' with message 'The OAuth 2.0 access token has expired, and a refresh token is not available. Refresh tokens are not returned for responses that were auto-approved.' in /home/mathcelebrity/public_html/Google/Auth/OAuth2.php:227
So I found this thread and tried reply #5 and get the error above:
How to refresh token with Google API client?
All I want this thing to do is run nightly with no approval needed. In the background.
<?php
require_once 'templates/base.php';
session_start();
include('config.php');
set_include_path('/path/to/clientlib' . PATH_SEPARATOR . get_include_path());
set_include_path('/path/to/clientlib' . PATH_SEPARATOR . get_include_path());
require_once 'Google/Client.php';
require_once 'Google/Service/AdSense.php';
require_once 'Google/Service/AdSense.php';
// Autoload example classes.
include 'examples/GetAllAccounts.php';
include 'examples/GetAccountTree.php';
include 'examples/GetAllAdClients.php';
include 'examples/GetAllAdUnits.php';
include 'examples/GetAllCustomChannelsForAdUnit.php';
include 'examples/GetAllCustomChannels.php';
include 'examples/GetAllAdUnitsForCustomChannel.php';
include 'examples/GetAllUrlChannels.php';//GetAllUrlChannels
include 'examples/GenerateReport.php';//GenerateReport
include 'examples/GenerateReportWithPaging.php';//GenerateReportWithPaging
include 'examples/FillMissingDatesInReport.php';//FillMissingDatesInReport
include 'examples/CollateReportData.php';//CollateReportData
include 'examples/GetAllSavedReports.php';//GetAllSavedReports
include 'examples/GenerateSavedReport.php';//GenerateSavedReport
include 'examples/GetAllSavedAdStyles.php';//GetAllSavedAdStyles
include 'examples/GetAllAlerts.php';//GetAllAlerts
include 'examples/GetAllDimensions.php';//GetAllDimensions
include 'examples/GetAllMetrics.php';//GetAllMetrics
// Max results per page.
define('MAX_LIST_PAGE_SIZE', 50, true);
define('MAX_REPORT_PAGE_SIZE', 50, true);
// Configure token storage on disk.
// If you want to store refresh tokens in a local disk file, set this to true.
define('STORE_ON_DISK', true, true);
define('TOKEN_FILENAME', 'tokens.dat', true);
// Set up authentication.
$client = new Google_Client();
$client->addScope('https://www.googleapis.com/auth/adsense.readonly');
$client->setAccessType('offline');
// Be sure to replace the contents of client_secrets.json with your developer
// credentials.
$client->setAuthConfigFile('client_secrets.json');
// Create service.
$service = new Google_Service_AdSense($client);
// If we're logging out we just need to clear our local access token.
// Note that this only logs you out of the session. If STORE_ON_DISK is
// enabled and you want to remove stored data, delete the file.
if (isset($_REQUEST['logout'])) {
unset($_SESSION['access_token']);
}
// If we have a code back from the OAuth 2.0 flow, we need to exchange that
// with the authenticate() function. We store the resultant access token
// bundle in the session (and disk, if enabled), and redirect to this page.
if (isset($_GET['code'])) {
$client->authenticate($_GET['code']);
// Note that "getAccessToken" actually retrieves both the access and refresh
// tokens, assuming both are available.
$google_token = json_decode($_SESSION['access_token']);
$client->refreshToken($google_token->refresh_token);
$_SESSION['access_token'] = $client->getAccessToken();
if (STORE_ON_DISK) {
file_put_contents(TOKEN_FILENAME, $_SESSION['access_token']);
}
$redirect = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF'];
header('Location: ' . filter_var($redirect, FILTER_SANITIZE_URL));
exit;
}
// If we have an access token, we can make requests, else we generate an
// authentication URL.
if (isset($_SESSION['access_token']) && $_SESSION['access_token']) {
$client->setAccessToken($_SESSION['access_token']);
} else if (STORE_ON_DISK && file_exists(TOKEN_FILENAME) &&
filesize(TOKEN_FILENAME) > 0) {
// Note that "setAccessToken" actually sets both the access and refresh token,
// assuming both were saved.
$client->setAccessToken(file_get_contents(TOKEN_FILENAME));
$_SESSION['access_token'] = $client->getAccessToken();
} else {
// If we're doing disk storage, generate a URL that forces user approval.
// This is the only way to guarantee we get back a refresh token.
if (STORE_ON_DISK) {
$client->setApprovalPrompt('force');
}
$authUrl = $client->createAuthUrl();
}
//echo pageHeader('Get Final Report');
//echo "stre on disk = " . STORE_ON_DISK . "<br />";
echo '<div><div class="request">';
if (isset($authUrl)) {
echo '<a class="login" href="' . $authUrl . '">Login !</a>';
} else {
echo '<a class="logout" href="?logout">Logout</a>';
};
echo '</div>';
if ($client->getAccessToken()) {
echo '<pre class="result">';
// Now we're signed in, we can make our requests.
$adsense = makeRequests($service);
/* Note that we re-store the access_token bundle, just in case anything
changed during the request - the main thing that might happen here is the
access token itself is refreshed if the application has offline access. */
$_SESSION['access_token'] = $client->getAccessToken();
echo '</pre>';
}
echo '</div>';
echo pageFooter(__FILE__);
// Makes all the API requests.
function makeRequests($service) {
print "\n";
$accounts = GetAllAccounts::run($service, MAX_LIST_PAGE_SIZE);
echo '<div class="Account">Account No. '.$accounts[0]["id"].' Details</div>';
if (isset($accounts) && !empty($accounts)) {
// Get an example account ID, so we can run the following sample.
$exampleAccountId = $accounts[0]['id'];
GetAccountTree::run($service, $exampleAccountId);
$adClients =
GetAllAdClients::run($service, $exampleAccountId, MAX_LIST_PAGE_SIZE);
;
?>
<table id="myTable" class="tablesorter" border="1px solid">
<thead>
<tr>
<th>AdClient ID</th>
<th>AdClient Code</th>
</tr>
</thead>
<tbody>
<?php
foreach($adClients as $adClients){
?>
<tr><td><?php echo $adClients['id']; ?></td><td><?php echo $adClients['productCode']; ?></td></tr>
<?php
}
?>
</tbody>
</table>
<?php
if (isset($adClients) && !empty($adClients)) {
// Get an ad client ID, so we can run the rest of the samples.
$exampleAdClient = end($adClients);
$exampleAdClientId = $adClients['id'];
$adUnits = GetAllAdUnits::run($service, $exampleAccountId,
$exampleAdClientId, MAX_LIST_PAGE_SIZE);
?>
<table id="myTable_1" class="tablesorter" border="1px solid">
<thead>
<tr>
<th>AdUnit name</th>
<th>AdUnit Code</th>
<th>AdUnit ID</th>
<th>Status</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
<?php
foreach($adUnits as $adUnits){
if($adUnits['status']=='ACTIVE' ||$adUnits['status']=='NEW'){ ?>
<tr>
<td><?php echo $adUnits['name']; ?></td>
<td><?php echo $adUnits['code']; ?></td>
<td><?php echo $adUnits['id']; ?></td>
<td><?php echo $adUnits['status']; ?></td>
<td class="link">Get detail</td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<?php
if (isset($_REQUEST['ad_name'])) {
//die('function shoul be calle dhere ');
$Get_reports=GenerateReport::run($service, $exampleAccountId, $exampleAdClientId,$_REQUEST['ad_name']);
}
else {
$Get_reports=GenerateReport::run($service, $exampleAccountId, $exampleAdClientId);
}
//print_r($Get_reports);
?>
<table id="myTable_2" class="tablesorter" border="1px solid">
<thead>
<tr>
<?php foreach($Get_reports['headers'] as $headers){
?>
<th><?php printf('%25s', $headers['name']); ?></th>
<?php
}
?>
</tr>
</thead>
<?php
foreach($Get_reports['rows'] as $rows) {
?>
<tr>
<?php
foreach($rows as $col) {
?>
<td><?php echo $col; $adsense = $col; ?></td>
<?php
} ?>
</tr>
<?php
}
?>
</table>
<table id="myTable_3" class="tablesorter" border="1px solid">
<thead>
<tr>
<?php
foreach($Get_reports['headers'] as $headers){
?>
<th><?php echo 'Total '.$headers['name']; ?></th>
<?php
}
?>
</tr>
</thead>
<tbody>
<tr>
<?php
foreach($Get_reports['totals'] as $totals){
?>
<td><?php echo $totals; ?></td>
<?php
}
?>
</tr>
</tbody>
</table>
<?php
//die('Report Generated For Last 7 Days');
}
}
//echo "adsense = " . $adsense . "<br />";
return $adsense;
}
?>
Don't try using a service account - normally the right choice but they wont work with AdSense.
Try changing this line so that the path is absolute
define('TOKEN_FILENAME', '/real/path/here/tokens.dat', true);
make sure that when you hit it once by hand, the file appears and has data (You can open it - should be json)

Codeigniter Get Nested Hierarchical Data from Database

How can i get Hierarchical Data from db in Codeigniter. I read this :
http://www.sitepoint.com/hierarchical-data-database/
And i do good that but i cant optimize this tutorial with my model, controler and views
Default Category
|----- Sub category
| ----One more category
|----- Somthing else
I try but dont show sub category:
My model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$this->data[$row->id] = $row;
//echo str_repeat(' ',$level).$row['title']."\n";
}
return $this->data;
}
Controller :
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
Views:
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th> <?php echo str_repeat('|----', 0+1). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>
And output is :
----Default
----Default
----Test Category 1
----Seccond Test Category 1
----Another Test Category 1
When i do this in model all work fine but when i try that to call in controler and loop in view i have result like above example:
This work onlu in model:
public function fetchChildren($parent, $level) {
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
echo str_repeat('|-----',$level).$row->title."\n";
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
And like output i have :
Default
|----Test Category 1
|----Seccond Test Category 1
|----Another Test Category 1
Any one have solution or example thanks.
Try storing the level value for each category.
In your model:
public function fetchChildren($parent, $level){
$this->handler = $this->db->query("SELECT * FROM content_categories WHERE parent_id='".$parent."' ");
foreach($this->handler->result() as $row ) {
$row->level = $level;
$this->data[] = $row;
$this->fetchChildren($row->title, $level+1);
}
return $this->data;
}
In your controller:
$this->data['node'] = $this->categories_model->fetchChildren(' ',0);
In your view
<table class="module_table">
<thead>
<tr>
<th><?php echo lang('categories_table_title'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($node as $row) : ?>
<tr>
<th><?php echo str_repeat('|----', $row->level). $row->title ?> </th>
</tr>
<?php endforeach; ?>
</tbody>
</table>

CakePHP Ajax Pagination

I am currently trying to get an ajax paginated list working. I think I'm close. When I click on the Previous, Next or individual page numbers, the correct results show but div.postsPaging is loaded with the paginated results along with Cake's default.ctp layout's header and footer. I've tried setting the layout to ajax in the displayPosts view or in the displayPosts action, but then the default layout doesn't appear at all (either inside or outside the div).
My question is, how can I load the postsPaging div with just the paginated results and not the header, footer or anything else in the layout. How can I get the results of the ajax request to not include the header and footer of the default layout?
The jQuery events attached to one of the page indexes and the Next button are:
$("#link-196981051").bind("click", function (event) {$.ajax({dataType:"html", success:function (data, textStatus) {$("#postsPaging").html(data);}, url:"\/AuthAdminCakeApp\/posts\/displayPosts\/page:2"});
return false;});`
$("#link-296431922").bind("click", function (event) {$.ajax({dataType:"html", success:function (data, textStatus) {$("#postsPaging").html(data);}, url:"\/AuthAdminCakeApp\/posts\/displayPosts\/page:2"});
return false;});`
My PostsController code looks like this:
class PostsController extends AppController {
public $helpers = array('Js' => 'Jquery');
public $paginate = array(
'limit' => 3,
'order' => array(
'Post.title' => 'asc'
)
);
public function displayPosts() {
$this->set('posts', $this->paginate());
}
// other actions
}
My paging element (paging.ctp) looks like this:
<?php
$this->Paginator->options(
array('update'=>'#postsPaging',
'url'=>array('controller'=>'posts',
'action'=>'displayPosts')));
?>
<table cellpadding="0" cellspacing="0">
<tr>
<th><?php echo $this->Paginator->sort('id'); ?></th>
<th><?php echo $this->Paginator->sort('user_id'); ?></th>
<th><?php echo $this->Paginator->sort('title'); ?></th>
<th><?php echo $this->Paginator->sort('body'); ?></th>
<th><?php echo $this->Paginator->sort('created'); ?></th>
<th><?php echo $this->Paginator->sort('modified'); ?></th>
<th class="actions"><?php echo __('Actions'); ?></th>
</tr>
<?php
foreach ($posts as $post): ?>
<tr>
<td><?php echo h($post['Post']['id']); ?> </td>
<td>
<?php echo $this->Html->link($post['User']['id'], array('controller' => 'users', 'action' => 'view', $post['User']['id'])); ?>
</td>
<td><?php echo h($post['Post']['title']); ?> </td>
<td><?php echo h($post['Post']['body']); ?> </td>
<td><?php echo h($post['Post']['created']); ?> </td>
<td><?php echo h($post['Post']['modified']); ?> </td>
<td class="actions">
<?php echo $this->Html->link(__('View'), array('action' => 'view', $post['Post']['id'])); ?>
<?php echo $this->Html->link(__('Edit'), array('action' => 'edit', $post['Post']['id'])); ?>
<?php echo $this->Form->postLink(__('Delete'), array('action' => 'delete', $post['Post']['id']), null, __('Are you sure you want to delete # %s?', $post['Post']['id'])); ?>
</td>
</tr>
<?php endforeach; ?>
</table>
<?php
echo $this->Paginator->prev('< ' . __('previous'), array(), null, array('class' => 'prev disabled'));
echo $this->Paginator->numbers(array('separator' => ''));
echo $this->Paginator->next(__('next') . ' >', array(), null, array('class' => 'next disabled'));
?>
The view for the displayPosts action looks like this:
<div id="postsPaging">
<?php echo $this->element('Posts/paging'); ?>
</div>
Edit:
I'm using CakePHP 2.2.5.
you have to use an ajax layout.
$this->layout = ($this->request->is("ajax")) ? "ajax" : "default";
You can also place this code snippet in AppController, for Ajax responses application wide.
public function beforeRender() {
$this->layout = ($this->request->is("ajax")) ? "ajax" : "default";
}
Also make sure you are loading the RequestHandler component.
var $components = array('RequestHandler');
Putting the above in your Controller or AppController will handle setting the layout to ajax.

Joomla plugin database mistakes? What is wrong here?

i've just started learning Jplugin development, so here i made a little voting script. Everything here works fine, but i want conf.php file to be made in joomla framework style. As you see here, 1 and 2 files works perfectly together. I want to use third example instead of second, in which i use simple php code. The last example i tried to do is using joomla framework, but it doesnt work. I have no idea what's wrong with that code. Anyone see could tell where I made a mistake or maybe far away from doing it right ?
<?php
defined( '_JEXEC' ) or die;
?>
<?php
class plgSystemRatingx extends JPlugin
{
public function onContentBeforeDisplay()
{
?>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".like").click(function()
{
var id=$(this).attr("id");
var name=$(this).attr("name");
var dataString = 'id='+ id + '&name='+ name;
$("#votebox").slideDown("slow");
$("#flash").fadeIn("slow");
$.ajax
({
type: "POST",
url: "conf.php",
data: dataString,
cache: false,
success: function(html)
{
$("#flash").fadeOut("slow");
$("#content").html(html);
}
});
});
$(".close").click(function()
{
$("#votebox").slideUp("slow");
});
});
</script>
<body>
<div style="margin:50px">
Like -- Dislike
<div id="votebox">
<span id='close'>X</span>
<div style="height:13px">
<div id="flash">Loading........</div>
</div>
<div id="content">
</div>
</div>
</div>
<?php
return true;
}
}
this piece of code works perfectly
<?php
$mysql_hostname = "localhost";
$mysql_user = "px";
$mysql_password = "px";
$mysql_database = "jum";
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die("Opps some thing went wrong");
mysql_select_db($mysql_database, $bd) or die("Opps some thing went wrong");
if($_POST['id'])
{
$id=mysql_real_escape_string($_POST['id']);
$name=mysql_real_escape_string($_POST['name']);
mysql_query("update messages set $name=$name+1 where id='$id'");
$result=mysql_query("select up,down from messages where id='$id'");
$row=mysql_fetch_array($result);
$up_value=$row['up'];
$down_value=$row['down'];
$total=$up_value+$down_value;
$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
<div style="margin-bottom:10px">
<b>Ratings for this blog</b> ( <?php echo $total; ?> total)
</div>
<table width="700px">
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $up_value; ?></td>
<td width="600px"><div id="greebar" style="width:<?php echo $up_per; ?>%"></div></td>
</tr>
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $down_value; ?></td>
<td width="600px"><div id="redbar" style="width:<?php echo $down_per; ?>%"></div></td>
</tr>
</table>
<?php
}
?>
and this made in joomla style doesnt work at all
<?php
defined( '_JEXEC' ) or die;
?>
<?php
if(JRequest::getVar('id'))
{
$id = JRequest::getInt('id');
$name = JRequest::getInt('name');
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query2 = $db->getQuery(true);
$queryup = $db->getQuery(true);
$querydown = $db->getQuery(true);
$query->update('messages');
$query->set("message = 1");
$query->where("id = $id");
$query2->select('up,down');
$query2->from('messages');
$query2->where("id = $id");
$queryup->select('up');
$queryup->from('messages');
$queryup->where("id = $id");
$querydown->select('down');
$querydown->from('messages');
$querydown->where("id = $id");
$db->setQuery( $query );
$db->query();
$db->setQuery( $query2 );
$db->query();
$db->setQuery( $queryup );
$data0 = $db->query();
$db->setQuery( $querydown );
$data1 = $db->query();
$up_value= $db->insertid($data0);;
$down_value = $db->insertid($data1);
$total=$up_value+$down_value;
$up_per=($up_value*100)/$total;
$down_per=($down_value*100)/$total;
?>
<table width="700px">
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $up_value; ?></td>
<td width="600px"><div id="greebar" style="width:<?php echo $up_per; ?>%"></div></td>
</tr>
<tr>
<td width="30px"></td>
<td width="60px"><?php echo $down_value; ?></td>
<td width="600px"><div id="redbar" style="width:<?php echo $down_per; ?>%"></div></td>
</tr>
</table>
<?php
}
Try this
$query->where('id = ' . $db->qn($id));
etc

Codeigniter Paginaton Next button is not working

I am trying to display information from database. I have set $config['per_page'] to 2, in my view file I can see the information I want but when I click on the next button it doesn't change anything. The database values remain same and the current page remains the first page too.
Would you please kindly help me figure out the problem?
Thanks in Advance :)
Controller:
function index($id){
$this->load->library('pagination');
$config['base_url'] = site_url().'Student_fee_status/index/'.$id;
$this->db->select('*');
$this->db->from('studentpayment1');
$this->db->where('studentid', $id);
$query = $this->db->get('');
$numrows=$query->num_rows();
$config['total_rows'] = $numrows;
$config['per_page'] = 2;
$config['uri_segment'] = '2';
$config['num_links'] = 20;
$config['full_tag_open'] = '<div class="pagination" align="center">';
$config['full_tag_close'] = '</div>';
$this->pagination->initialize($config);
$this->load->model('Mod_student_fee_status');
$data['records']= $this->Mod_student_fee_status->fee_status($id,$config['per_page'],$config['uri_segment']);
$data['main_content']='view_student_fee_status';
$this->load->view('includes/template',$data);
}
My Model :
function fee_status($id,$perPage,$uri_segment) {
$this->db->select('*');
$this->db->from('studentpayment1');
$this->db->where('studentid', $id);
$getData = $this->db->get('', $perPage, $uri_segment);
if($getData->num_rows() > 0)
return $getData->result_array();
else
return null;
}
EDIT
When the page first loads the link looks like this- http://localhost/sundial/Student_fee_status/index/1006/
but when I click on the next page it looks like this- http://localhost/sundial/Student_fee_status/index/1006/2
My View File:
<h1>Payment Status</h1>
<?php if(count($records) > 0) { ?>
<table id="table1" class="gtable sortable">
<thead>
<tr>
<th>S.N</th>
<th>Invoice ID</th>
<th>Transaction Description</th>
<th>Received Date</th>
<th>Debit</th>
<th>Credit</th>
<th>Balance</th>
</tr>
</thead>
<?php $i = $this->uri->segment(2) + 0; foreach ($records as $row){ $i++; ?>
<tbody>
<?php
$mydate= $row['period'];
$month = date("F",strtotime($mydate));
$year = date("Y",strtotime($mydate));
?>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['invoiceid'];?></td>
<td><a href="<?php echo base_url(); ?>student_fee_status/fee_types/<?php echo $row['paymentid']; ?>" rel="1" class="newWindow" >Total Fee For <?php echo $month ;?>, <?php echo $year ;?> </a></td>
<td><?php echo $row['received_date'];?></td>
<td><?php echo $row['totalamount'];?></td>
<td><?php echo "0";?></td>
<td><?php echo $row['totalamount'];?></td>
</tr>
<tr>
<td><?php echo $i; ?>.</td>
<td><?php echo $row['invoiceid'];?></td>
<td>Payment Received </td>
<td><?php echo $row['received_date'];?></td>
<td><?php echo "0";?></td>
<td><?php echo $row['amountpaid'];?></td>
<td>
<?php
$balance=$row['totalamount']-$row['amountpaid'];
if($balance>0){
echo "<font color=\"red\">$balance</font>";
}
else {
echo $balance;
}
?>
</td>
</tr>
<?php } ?>
</tbody>
</table>
<?php } ?>
<div class="tablefooter clearfix">
<div class="pagination">
<?php echo $this->pagination->create_links(); ?>
</div>
</div>
You are telling the pagination library to use $config['uri_segment'] = '2'; - the second segment of your uri.
When this is your url: http://localhost/sundial/Student_fee_status/index/1006/ I am guessing this is your base_url: http://localhost/sundial/
In this case your segments are:
Student_fee_status - your controller
index - the controllers method you are calling
1006 - the argument you are calling the controllers method with
this should be the argument for pagination
Try this
$config['uri_segment'] = '4';
instead of
$config['uri_segment'] = '2';
edit:
$data['records']= $this->Mod_student_fee_status->fee_status($id,$config['per_page'],$config['uri_segment']);
I think this line contains another error.
You pass your model the information which uri_segment is used by the pagination library. That should be 4 now. However, your model uses this value to specify an offset in your query. This means you always put an offset of 4 into your query. But I think what you really want to do is, pass the model the VALUE of the 4th uri_segment.
I would try this instead:
$data['records']= $this->Mod_student_fee_status->fee_status($id,$config['per_page'],$this->uri->segment($config['uri_segment']));

Resources