Ajax Pagination Error in codeigniter - ajax

i have the following code which i modiefied from a tutorial
but the problem is that, i cant display the result properly in my view page..
if i display the array in the controller then its working properly, but in the view, its throwing the error..
<?php
class test extends CI_Controller {
public function index($start = 0) {
$this->load->model('pages_model');
$data_page=$this->pages_model->get_pages();
$this->load->helper('url');
$this->load->library('pagination');
$config['base_url'] = base_url().'test/index';
$config['total_rows'] = count($data_page);
$config['per_page'] = 5;
$data['user'] = array();
for($i=$start; $i<$start+$config['per_page']; $i++)
{
if (isset($data_page[$i])) {
$data['user'] = $data_page[$i];
}
}
//print_r($data['user']['page_id']); // this line displays 3, since the tupple with id 3 has maximum priority 5
$this->pagination->initialize($config);
$data['pagination'] = $this->pagination->create_links();
if ($this->input->post('ajax')) {
$this->load->view('test', $data);
} else {
$this->load->view('test', $data);
}
}
}
?>
now comes the model
<?php
class pages_model extends CI_Model{
function __construct() {
parent::__construct();
}
function get_pages()
{
return $this->db->query("SELECT * FROM td_pages ORDER BY page_priority ASC")->result_array();
}
}
?>
and finally the view
<!DOCTYPE html>
<html>
<header>
<title>CodeIgniter Ajax Jquery Pagination</title>
<script src="<?php echo base_url(); ?>assets/front_assets/js/jquery-1.7.1.min.js"></script>
<script>
$(function() {
applyPagination();
function applyPagination() {
$("#ajax_paging a").click(function() {
var url = $(this).attr("href");
$.ajax({
type: "POST",
data: "ajax=1",
url: url,
beforeSend: function() {
$("#content").html("");
},
success: function(msg) {
$("#content").html(msg);
applyPagination();
}
});
return false;
});
}
});
</script>
</header>
<body>
<div id="content">
<div id="data">
<?php foreach($page_frag as $ut)
{?>
<div><?php echo $ut['page_slug'];?></div>
<?php } ?>
</data>
<div id="ajax_paging">
<?php echo $pagination; ?>
</div>
</div>
</div>
</body>
</html>
the problem is that the view is displaying the results in wrong way, but if i display in controller, then it shows that the array in the controller is working perfectly...
please help me solving the prob

You are loading the entire view in your ajax request which also contains the body and head text, Create a seperate view with the following content and load it in your ajax request.
<div id="data">
<?php foreach($page_frag as $ut)
{?>
<div><?php echo $ut['page_slug'];?></div>
<?php } ?>
</div>

What you're doing is WRONG
Pagination is meant to off-load processing power/ram from the server not only from the client side.
You're pulling off all your result then paginate them while you should be asking MySQL to paginate it for you & have a second query to give you the number of results to use it.
If you have index.php in your links then you must be using site_url() instead of base_url() & please note that both accepts an argument so you do not need to concatenate it the way you did it would be like this:
site_url('test/index');
codeigniter uses GET method, while in your javascript code you're using POST.
An easier method would be to catch the pagination li > a tags for the pagination & process it inside a container.

Related

How to add numeric pagination to Ajax result, that shows podcasts(custom post) filter by custom taxonomies

i would like to add numeric pagination (and load the posts dynamically) to this page, called 'page-podcast', where i filter, with Ajax call, my podcast (custom post), using these tags, genre, country and type: https://imgur.com/Qw8JOlC.
In my front end, page-podcast.php, i have this div, where post appears:
<div id="datafetch">Search results will appear here</div>
And in page function.php i added the function that call Ajax
add_action( 'wp_footer', 'ajax_fetch' );
function ajax_fetch() {
?>
<script type="text/javascript">
function fetch(e){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', keyword: keywords},
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
</script>
The following code is the ajax function (always on function.php):
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){
...filter part, omitted, because it has nothing to do with the question...
$the_query = new WP_Query($query_args);
if( $the_query->have_posts() ) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<h2><?php the_title();?></h2>
<?php endwhile;
else: ?>
<p class="no-criteria"><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php
wp_reset_postdata();
endif;
die();
}
Someone has some tips/examples/code to share? Because i tried many solution that i find on the web, but nothing works.
Resolved.
So, i have added the number of the pages within the ajax function, before the end of the loop:
<?php if ($numberPages > 1): ?>
<ul>
<?php
for ($i = 1; $i <= $numberPages; $i++) {
echo '<li><a name="page" href="#" class="pagination" value="' . $i . '">'
. $i . '</a></li>';
}
?>
</ul>
$numberPages is equal to:
$the_query = new WP_Query($query_args);
$numberPages = $the_query->max_num_pages;
I create a global variable, call $page, set to 0.
Then i worked on my two event:
$(document).on("click touchend", ".premuto", function (event) {
event.preventDefault();
page = 1;
keywords['page'] = page;
keywords[$(this).attr('name')] = $(this).attr('value');
fetch(this);
});
$(document).on("click touchend", ".pagination", function (event) {
event.preventDefault();
keywords[$(this).attr('name')] = $(this).attr('value');
fetch(this);
});
".premuto" is an element that contain the id i want to pass to ajax (custom taxonomy) and page is set to 1.
".pagination" is the list of post's page number (1,2,...).
Finally, on my ajax function, i get the page number:
$paged = $_POST['keyword']['page'];
and in my wp_query i added:
'posts_per_page' => '2',
'paged' => $paged,

Polling Chat message content to screen using ajax JSON

Hi I successfully designed a chat message system between users and it works fine. The only problem I am having at this point is polling data from chat table to browser real time.
The messages are displayed using ajax and the setInterval works as I checked the console. The issue is that it does not capture new entries to the table for display and hence the user has to keep refreshing the page to see new content.
Please help. My code is below. Please forgive my file naming convention as I will change it later on.
PS this is developed using codeigniter framework.
**Chats.php - Controller**
public function ajax_get_chat_messages(){
echo $this->_get_chat_messages();
}
function _get_chat_messages($recipient = null)
{
$user_id = $this->session->userdata('user_id');
$recipient = $this->input->post('recipient');
$data['recipient'] = $this->User_model->get_users($user_id);
$data['chats_count'] = $this->Chats_model->get_chat_messages_count($recipient);
$content = $this->Chats_model->get_chat_messages_count($recipient);
$data['chats'] = $this->Chats_model->get_chat_messages($user_id);
$result = array('status' =>'ok', 'content'=>$content);
return json_encode($result);
}
**Model - Chats_model.php**
public function get_chat_messages_count($recipient = null){
$session = $this->session->userdata('user_id');
$this->db->select('*');
$this->db->from('chat_messages');
$this->db->join('users', 'users.user_id = chat_messages.user_id');
$this->db->where(array('chat_messages.user_id' => $session));
$this->db->where(array('chat_messages.recipient' => $recipient));
$this->db->or_where(array('chat_messages.user_id' => $recipient));
$this->db->where(array('chat_messages.recipient' => $session));
$this->db->where_in(array('chat_messages.chat_id' => $session , $recipient));
$query = $this->db->get();
return $query->result_array();
}
**View - chats_view.php**
<script type="text/javascript">
var user = "<div class='timeline-item' id='view'><ul><?php foreach($chats_count as $chat){echo '<li>'; echo $chat['username']; echo '</li>'; }?></ul></div>";
</script>
<div class="wrapper wrapper-content">
<div class="row animated fadeInRight">
<div class="col-lg-12">
<div class="ibox float-e-margins">
<div class="ibox-title">
<h5>Chat</h5>
<div class="ibox-tools" >
</div>
</div>
<div class="ibox-content inspinia-timeline" id="view1" >
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
**JS - chat2.js**
$(document).ready(function(){
setInterval(function() { get_chat_messages(); }, 2500)
$("input#chat_message").keypress(function(e){
if(e.which == 13){
$("a#submit_message").click();
return false;
}
});
function get_chat_messages(){
$.post(base_url +"user/chats/ajax_get_chat_messages",{user: user}, function(data) {
if(data)
{
var current_content = $("#view1").html();
$("#view1").html(user);
console.log(user);
}
else
{
}, "json");
}
get_chat_messages();
});
Images attached showing the table structure, the chat page on browser and console data.
[Chat page on browser, only showing username for testing purposes][1]
[Chat Table][2]
[Console Data, only showing username for testing purposes][3]

i want to search in codeigniter and view result is which i searched

Here is my Model:
function get_search() {
$match = $this->input->post('search');
$this->db->like('p_category',$match);
$this->db->or_like('p_place',$match);
$this->db->or_like('p_price',$match);
$query = $this->db->get('tbl_property');
if($query->num_rows() > 0)
return $query->result();
else
return FALSE;
}
Here is my View:
<?php
foreach($query as $pack_details):
?>
<table class="table table-hover table-bordered">
<?php echo $pack_details->p_title?>
</table>
<?php
endforeach;?>
want to search and will show result only which i searched.
This is an old one of mine, but you may be able to adapt it to yours. Your form sends the post to the controller. The variable $art is the search item. The variable $num is the number of results. The jquery sends the form to the article class search_results
Controller
public function seek()
{
// this is the artist search display
$art = html_escape(trim($this->input->post('art')));
$this->db->like('artist', $art);
$this->db->select('artist, song, album, mix_name');
$query = $this->db->get('podcasts');
$num = $query->num_rows();
echo "<h3>We found $num $art song's</h3>";
if($query->num_rows() > 0) {
foreach ($query->result() as $row) {
echo "<li class='search_list'>Song: $row->song <br> Album: $row->album <br> Podcast: $row->mix_name</li> ";
}
}else {
echo "You searched for $art, Please check your spelling, or ensure the artists name is complete";
}
}
Jquery if you want the search to show up on the same page
$(function () {
"use strict";
$("#search").submit(function () {
var data = $('#search').serialize();
//alert(data); return false;
$.ajax({
url: "/display/seek",
data: data,
type: "POST",
success: function (msg) {
$('article.search_results').html(msg).show();
}
});
return false;
});
});
View is simply. See the last line in the jquery
<article class="search_results"></article>

Ajax request in cakephp 2.x

I'm trying to send a simple ajax request in cakephp. I've to send ajax requests for many buttons. But I'm just trying a simple ajax request first. But it's not working for some reason. This is what I've done so far. This is my code.
show.ctp
<?php echo $this->Html->script('jquery', FALSE); ?>
<?php
echo $this->Form->create();
echo $this->Form->input('field', array('id'=>'field'));
echo $this->Js->submit('Send', array(
'before'=>$this->Js->get('#sending')->effect('fadeIn'),
'success'=>$this->Js->get('#sending')->effect('fadeOut'),
'update'=>'#success'
));
?>
<div id='sending' style="display:none"> Counz[dot]gif will be displayed </div>
<div id='success'></div>
controller
var $name = 'count';
public $helpers = array('Js' => array('Jquery'));
//var $helpers = array('Ajax', 'Javascript');
var $components = array('RequestHandler');
public function show(){
if($this->RequestHandler->isAjax()){
$this->render('success', 'ajax'); //ajax tells the layout it should use
}else{
$this->set('for_map', $this->count->find('all'));
}
}
success.ctp
<p>It's working</p>
Also ajax.ctp is there by default.
Please tell me what am I doing wrong. Thanks. :)
It's better not to post to self when doing ajax requests.
show.ctp
echo $this->Form->create('Count', array('action'=>'ajaxShow'));
controller
public function ajaxShow(){
$this->layout = 'ajax';
if($this->RequestHandler->isAjax()){
$this->render('success', 'ajax'); //ajax tells the layout it should use
}
}
I know this thread is very old but I'll just share my answer. You can just do normal ajax call, for example your url is 'users/items' type is GET then in your:
UsersController.php
public function items(){
// some logic to get items
$this->set('items',$items);
$this->layout = null; //remove default layout.
$this->render('ajax/items'); // here I use View/Users/ajax/items.ctp
}
items.ctp
//you can return json
<?php echo json_encode($items); ?>
//or
//your own format
<?php
foreach($items as $item){
//some output
}
?>
now that output in items.ctp will be in your js' success property. just make sure you parse the returned json.

Codeigniter Message: Undefined variable: infos

I am a newbie in CI. I used MY_Controller.php as main controller. I could open the ajax as the div#page loader. Now , My problem is although I load /about page, I get the database entries for the services model. How can i get the about table for the about controller ?
..
function render_page($view) {
if( ! $this->input->is_ajax_request() )
{
$this->load->view('templates/header', $this->data);
}
$this->load->view($view, $this->data);
if( ! $this->input->is_ajax_request() )
{
$this->load->view('templates/menu');
$this->load->view('templates/footer', $this->data);
}
}..
My services_model:
class Services_model extends CI_Model {
function getAll() {
$q = $this->db->get('services');
if($q->num_rows() > 0){
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
}
My home controller :
public function view($page = 'home')
{
$this->load->helper('text');
$this->data['records']= $this->services_model->getAll();
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->render_page('pages/'.$page,$data);
}
When I use them in the home view there is no problem I can see the services_table :
<ul class="blog-medium">
<?php foreach($records as $row): ?>
<li>
<div class="blog-medium-text">
<h1><?php echo $row->title; ?></h1>
<p class="blog-medium-excerpt"><?php echo $row->content; ?><br />
Devamını Okumak için →</p>
</div>
<?php endforeach ?>
I want to use the same way in about page.
About_model:
class About_model extends CI_Model {
function getAll() {
$q = $this->db->get('abouts');
if($q->num_rows() > 0){
foreach ($q->result() as $row)
{
$data[] = $row;
}
return $data;
}
}
}
About controller :
public function view($page = 'about')
{
$this->load->helper('text');
$this->data['records']= $this->about_model->getAll();
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->render_page('pages/'.$page,$data);
}
And this is my view file of about :
<div id="content">
<?php foreach($infos as $row): ?>
<h3 style="text-align: center;"> <?php echo $row->title; ?></h3>
<div class="hr"> </div>
<?php echo $row->content; ?>
<?php endforeach; ?>
I get the error telling me :
Severity: Notice
Message: Undefined variable: infos
Filename: pages/about.php
Line Number: 3
Why cant i get the abouts table?
You are calling a variable $infos in your foreach, but it is never passed in as a variable to your view.
Read the docs about Adding Dynamic Data to the View
You will either need to set $data['infos'] to something or, and I'm guessing this what you intended, use $records in your foreach
The above answers your specific, but after you provided the repo for your source, there are issues you are struggling with. I highly suggest you read through the entire documentation, staring with the Introduction: Getting Started, continuing to the Tutorials and then General Topics.
The reason you are having problems here, you have your routes.php setup to that everything is routed into the Home controller executing the view method. This method, while it accepts the page you want to see is always returning a fetch of the services model. Your other controllers are not getting executed at all. Based on your controller setup, if you would just remove the custom route, http://theurl/about would route to the About Controller. The default method to be loaded is index so if you change view to index, then it would be displayed by default.

Resources