How to use ajax with codeigniter's modules - ajax

I have a page written in codeigniter framework.
Now I want to add a button to page (eg 'show more') that will get data with 'ajax.php' from the database and display them on the site, but I do not want it separately connect to the database and then get the results, just want to be able to collect data (in ajax.php) as well as in codeigniter controllers (using models)...
Hope you understand me :)

Here you go just add view more button and call this js and ajax function..This is code i have used please see it and use it as per your requirment
$('.more').live("click",function()
{
var this_tag = $(this);
var ID = $(this).attr("id");
if(ID)
{
$("ol#updates").addClass('tiny-loader');
this_tag.html('Loading.....');
$.post(siteUrl+"ajax/ajax_more",{lastmsg:ID,restid:$(this_tag).data("restid")},function(html){
$("ol#updates").removeClass('tiny-loader');
$("ol#updates").append(html);
$("#more"+ID).remove();// removing old view-more button
});
}
else
{
this_tag.fadeOut('slow');// no results
}
return false;
});
code in ajax file
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Ajax_more extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('general_model');
$this->limit =REVIEW_DETAIL;
}
public function index($offset = 0)
{
$lastmsg=$this->input->post('lastmsg');
$rest_id=$this->input->post('restid');
$value=('reviews.*,usermaster.Name as User');
$joins = array
(
array
(
'table' => 'tk_usermaster',
'condition' => 'usermaster.Id = reviews.UserId',
'jointype' => 'leftouter'
),
);
$this->results = $this->general_model->get_joinlist('reviews',$value,$joins,array('reviews.Status'=>'Enable','reviews.RestaurantId'=>$rest_id,'reviews.Id <'=>$lastmsg),'reviews.Id','desc',$this->limit,$offset);
$data['list_review']= $this->results['results'];
?>
<?php foreach ($data['list_review'] as $row): ?>
<div class="user_reviews_data" >
<div class="width-20 float-left">
<span class="padleft-10"><?php echo $row->User; ?> </span>
<br/>
<span class="padleft-10 "><div class="rateit" data-rateit-value="<?php echo $row->Rating;?>" data-rateit-ispreset="true" data-rateit-readonly="true"></div></span>
<div class="muted padleft-10 float-left"><small><?php echo date('dS M Y' ,strtotime($row->CreatedDate)); ?></small></div>
</div>
<div class="width-80 float-left"><?php echo $row->Feedback;?></div>
<span class="report_span">Report this Feedback <img src="<?php echo base_url();?>themes/images/FLAG_GREY.png"></span>
</div>
<?php
$msg_id = $row->Id;
endforeach; ?>
</div>
<div id="more<?php echo #$msg_id; ?>" class="btn-container center_text morebox">
View More
</div>
<?php
}
}

Related

change URL parameter in Codeignitor

I'm trying to change the URL parameter from the row ID to the NAME of the article. here is my code
Controllers
public function view($id=0)
{
if( !isset($id) || !is_numeric($id) ) {
redirect(base_url());
}
$tot = $this->Model_service->service_check($id);
if(!$tot) {
redirect(base_url());
}
and the view is
<?php
foreach ($services as $row) {
?>
<div class="col-lg-4 col-md-6">
<div class="services-item effect-item">
<a href="<?php echo base_url(); ?>service/<?php echo $row['name']; ?>" class="image-effect">
<div class="services-photo" style="background-image: url(<?php echo base_url(); ?>public/uploads/<?php echo $row['photo']; ?>)"></div>
</a>
<div class="services-text">
<h3><?php echo $row['name']; ?></h3>
<p>
<?php echo nl2br($row['short_description']); ?>
</p>
<div class="button-bn">
<?php echo READ_MORE; ?> <i class="fa fa-chevron-circle-right"></i>
please help me with the most simplified answer thank you
Yo need to change your article view function in controller. Lookup article name instead of id. But name might contains spaces which is not URL friendly so using concept of slug will solve this.
public function view($slug='')
{
if($slug == '') {
redirect(base_url());
}
$tot = $this->Model_service->find_service_by_slug($slug);
if(!$tot) {
redirect(base_url());
}
Reference link for concept of slug is https://codeigniter.com/user_guide/tutorial/news_section.html

Filter AJAX search results in WordPress by page template

I am making a WordPress website, which is made up of a Woocommerce Store + Blog section. Both in the Store and on the Blog there is a search engine that shows instant results with AJAX. What I want to do is that, depending on the page where the user is (Blog page or Store page), the search engine will only show results of articles or products, respectively.
After googling and testing, I understood that the conditional tags of Wordpress (is_home (), is_shop (), etc) don't work if they are called from the functions.php file, and the AJAX php function I'm using is effectively inside the functions.php.
The AJAX php function is as follows:
<?php
/**
* Adding ajax search functionality to the theme
*/
add_action('wp_ajax_nopriv_ajax_search','ajax_search');
add_action('wp_ajax_ajax_search','ajax_search');
function ajax_search(){
global $post;
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
's' =>$_POST['term'],
'posts_per_page' =>10
);
$query = new WP_Query( $args );
// display results
if( $query->have_posts() ) : ?>
<?php while( $query->have_posts() ) : $query->the_post(); ?>
<li>
<?php
$terms = get_the_terms( $post->ID, 'category' );
foreach ($terms as $term) {
break;
} ?>
<a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a>
<div class="clear"></div>
</li>
<?php endwhile;
wp_reset_postdata(); ?>
<?php else: ?>
<li class="no-results-ajax">No results.</li>
<?php endif; ?>
<?php exit;
}
?>
The JQuery function linked with the previous function is as follows:
function buscar_ajax(input1, input2) {
input1.keyup(function(e) {
// prevent browser autocomplete
jQuery(this).attr('autocomplete','off');
// get search term
var searchTerm = jQuery(this).val();
var urlFull = window.location.href; // URL completa
var ruta = window.location.pathname; // URL sin "http://dominio.com"
var dominio = urlFull.replace(ruta,''); // URL solo "http://dominio.com"
if(searchTerm.length > 2) {
jQuery.ajax({
url: dominio + "/wp-admin/admin-ajax.php",
type:"POST",
data:{
'action':'ajax_search',
'term' :searchTerm
},
success:function(result){
input2.fadeIn(200).html(result);
}
});
} else {
input2.fadeOut(200);
}
if(searchTerm.length == 0){
input2.hide();
}
if(e.keyCode == 27){
jQuery(this).val('');
input2.hide();
}
jQuery('body').click(function(e){
if ( !jQuery(e.target).hasClass("busqueda") ) {
input2.fadeOut(200);
jQuery(this).val('');
}
});
});
input1.keypress(function(e) {
if(e.keyCode == 27){
jQuery(this).val('');
input2.fadeOut(200);
}
});
}
var buscaHead1 = jQuery('input#s');
var buscaHead2 = jQuery('ul#dhemy-ajax-search');
buscar_ajax( buscaHead1, buscaHead2 );
And the HTML code of the search form:
<form role="search" method="get" id="buscador-blog" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input class="busqueda" type="text" value="" name="s" id="s" placeholder="Busca en el blog..."/>
<ul id="dhemy-ajax-search"></ul> <!-- AJAX search -->
<input type="submit" id="searchsubmit" value="" />
<input type="hidden" name="search-type" value="post" />
</form>
So far, the result is that AJAX shows blog articles or products or articles and products. (changing 'post' to 'product' in the 'post_type' parameter of the $ args array). I need that, if the person is on the Store page, they only show products and if they are on the Blog page, they only show posts.
This could be done if only I had some conditional to evaluate what type of page the user is viewing, and that is where I am trapped.
I very much appreciate any help or guidance you can give me.

Codeigniter after insert success message show in view

I am new in Codeigniter and I need to show success and error message after insert data's in database.
How can I show the message in the view page?
This is my coding:
Model
function addnewproducts($data)
{
if($data['product_name']!="" && $data['product_qty']!="" && $data['product_price']!="" && $data['date']!="")
{
$res=$this->db->insert('product_list',$data);
return $this->db->insert_id();
}
else
{
return false;
}
}
Controller
function addnewproduct()
{
$this->load->model('products');
$data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name'))));
$data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty'))));
$data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price'))));
$data['datetime']=date('d-m-Y');
$res = $this->products->addnewproducts($data);
if($res==true)
{
$data['success'] = 'Successful';
$this->load->view('addproduct',$data);
}
}
View
<p><?php echo $success; ?></p>
There are many ways but below is which i recommend:
Set temp session in controller on success or error:
$res = $this->products->addnewproducts($data);
if($res==true)
{
$this->session->set_flashdata('success', "SUCCESS_MESSAGE_HERE");
}else{
$this->session->set_flashdata('error', "ERROR_MESSAGE_HERE");
}
In View you can display flashdata as below:
echo $this->session->flashdata('success');
or
echo $this->session->flashdata('error');
Source : Codeigniter official website https://codeigniter.com/userguide3/libraries/sessions.html
I appreciate that you got your answer but I think flash data is bit old now, as we can use bootstrap to alert if any error and that looks good to on web page.
In controller
$res = $this->products->addnewproducts($data);
if($res==true)
{
$this->session->set_flashdata('true', 'write_the_message_you_want');
}
else
{
$this->session->set_flashdata('err', "write_the_message_you_want");
}
In View
<?php
if($this->session->flashdata('true')){
?>
<div class="alert alert-success">
<?php echo $this->session->flashdata('true'); ?>
<?php
} else if($this->session->flashdata('err')){
?>
<div class = "alert alert-success">
<?php echo $this->session->flashdata('err'); ?>
</div>
<?php } ?>
Controller:
function addnewproduct()
{
$this->load->model('products');
$data['product_name'] = trim(strip_tags(addslashes($this->input->post('product_name'))));
$data['product_qty'] = trim(strip_tags(addslashes($this->input->post('product_qty'))));
$data['product_price'] = trim(strip_tags(addslashes($this->input->post('product_price'))));
$data['datetime']=date('d-m-Y');
if($this->products->addnewproducts($data));
{
$this->session->set_flashdata('Successfully','Product is Successfully Inserted');
}
else
{
$this->session->set_flashdata('Successfully','Failed To
inserted Product');
}
// redirect page were u want to show this massage.
redirect('Controller/Fucntion_name','refresh');
}// close function
view :
On Redirect Page write This code top of Form
<?php if($responce = $this->session->flashdata('Successfully')): ?>
<div class="box-header">
<div class="col-lg-6">
<div class="alert alert-success"><?php echo $responce;?></div>
</div>
</div>
<?php endif;?>

can't use multiple ajaxLink for loading CJuiDialog widget

I have a problem when using multiple ajaxLink for loading CJuiDialog widget in yii. I'm using multiple dropdowns, each dropdown's value determine next dropdown.
Here is my code for viewing first dropdown and a link to create new item using Cdialog widget.
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'enableAjaxValidation'=>false,
)); ?>
<div class="row">
<?php
echo $form->labelEx($model,'uname'); ?>
<?php echo $form->dropDownList($model,'uname',$model- >getUniversityList(),array('onchange'=>'getSchemes(this.value)','empty'=>'Select university')); ?>
<?php echo $form->error($model,'uname'); ?>
<?php //create university dialoge box
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new university',array('university/dialoge'),array(
'success'=>'js:function(data){
$("#createUniversity").dialog("open");
document.getElementById("create_university").innerHTML=data;
}'));
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createUniversity',
'options'=>array(
'title'=>'Create University',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_university'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="scheme">
</div>
</div>
<?php $this->endWidget(); ?>
</div>
<input type="hidden" id="url" value="<?php echo $this->createUrl('scheme/test'); ?>">
this works pretty good.
here is the javascript code for loading next dropdown in the same view file
<script type="text/javascript">
function getSchemes(uid)
{
if(uid==""){
document.getElementById("scheme").innerHTML='';
return;
}
jQuery(function($){
var url=document.getElementById("url").value;
$.post(url, { uid:uid },
function(data){
document.getElementById("scheme").innerHTML=data;
document.getElementById("scheme_link").style.display="block";
});
});
}
The scheme drop down is loaded as the scheme view code is
<?php $cs = Yii::app()->getClientScript();
$cs->registerCoreScript("jquery");
?>
<?php
echo "<div class=".'label'."><label for=".'sch'.">Scheme</label></div>";
echo "<select id=".'sch'." onchange='getDepartments(this.value);'>";
echo "<option value=".''.">"."Select Scheme</option>";
foreach($schemes as $s)
{
echo "<option value='".$s->schemeid."' >".$s->scheme_name."</option>";
}
echo "</select>";
?>
<?php
if(!Yii::app()->user->isGuest)
{
echo CHtml::ajaxLink('create new Scheme',array('scheme/dialoge','id'=>5),array(
'success'=>'js:function(data1){
$("#createScheme").dialog("open");
document.getElementById("create_scheme").innerHTML=data;
}'));?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'createScheme',
'options'=>array(
'title'=>'Create Scheme',
'autoOpen'=>false,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
),
));
echo "<div id='create_scheme'></div>";
$this->endWidget('zii.widgets.jui.CJuiDialog');
}
?>
<div id="department">
</div>
<input type="hidden" id="urldepart" value="<?php echo $this->createUrl('department/test'); ?> ">
the second ajaxLink is shown as create new scheme but on clicking the link it shows the old create university dialog box instead of create scheme.
The simplest solution for this is to create the ID of the element that is causing problems as random.
Try adding:
'id' => 'some-element'.uniqid() // avoid mutliple ajax request because of using live
in the $htmlOptions array of ajaxLink

Codeigniter multiple views for nested tab setup

I am struggling with nested tab markup generated via Codeigniter model calls and would welcome any insightful comments. The difficulty is that the markup generated has unwanted repetitions of blocks of project data. The use of multiple views which are not straightforwardly inter-connected is probably where the problems lie.
Here's the controller:
function projects() {
$this->load->model('msm_projects');
$data['cats']=$this->msm_projects->catid()->result_array();
$this->load->view('vup_projects', $data);
foreach ( $data['cats'] as $item )
{
$data2['projects']=$this->msm_projects->catproj($item['catid'])->result_array();
$this->load->view('vup_projects2', $data2);
}
}
The model:
function catid() {
return $this->db->query("SELECT DISTINCT catid, cat FROM category INNER JOIN projects ON catid = projcat WHERE projpub=1 ORDER BY catid ASC");
}
function catproj($catid) {
return $this->db->query("SELECT catid, cat, projcat, projid, projtit FROM projects INNER JOIN category ON projcat = catid WHERE projcat = $catid AND projpub=1 ORDER BY catid ASC");
}
Here are the views which are in two parts. I suspect this is where it's all going wrong. There's an imperfect join between the two views which I am having a hard time thinking about.
view 1 called 'vup_projects'
<div id="wrapper">
<div class="yui3-g">
<div class="yui3-u-1"><div id="topbloc"><img src="http://localhost/getop/base-images/topbloc.gif" width="800" height="50" align="middle"></div></div>
<div class="yui3-u-1">
<div id="navbloc">
<div id="linx">
<ul >
<li id="about"><?php echo anchor('cu_tya/about', 'about'); ?></li>
<li id="ourwork"><?php echo anchor('cu_projects/projects', 'projects'); ?></li>
<li id="contact"><?php echo anchor('cu_tya/contact', 'contact'); ?></li>
<li id="member"><?php echo anchor('cu_sites/pager', 'your page'); ?></li>
</ul>
</div>
</div>
</div>
<div class="yui3-u-1">
<div id="container">
<ul>
<?php
foreach ( $cats as $item ) // top tabs
{
echo '<li><a href=#fragment-'.$item['catid'].'><span>'.$item['cat'].'</span></a></li>';
}
?>
</ul>
And the second view vup_projects2
<?php foreach ( $cats as $item ) { ?> <!-- main divs -->
<div id="fragment-<?php echo $item['catid'];?>">
<ul>
<?php foreach ( $projects as $project )
{ ?>
<li>
<span><?php echo $project['projtit'];?></span></li>
<?php } ?>
</ul>
<?php foreach ( $projects as $project )
{ ?>
<div id="fragment-<?php echo $project['projid'];?>a" >
<?php echo $project['projtit'].' hooray';?>
</div>
<?php } ?>
</div>
<?php } ?>
</div> <!-- container -->
</div> <!-- YUI-UNIT-1-->
</div> <!-- YUI-GRID -->
</div> <!-- wrapper -->
foreach ( $data['cats'] as $item )
{
$data2['projects']=$this->msm_projects->catproj($item['catid'])->result_array();
$this->load->view('vup_projects2', $data2);
}
is your problem, you're looping the views for every item in $data['cats']... you're also doing a query for every $item. You should do one query and then loop through the results accordingly. But to fix your problem, try this:
foreach ( $data['cats'] as $item )
{
$data2['projects'][$item['catid']] = $this->msm_projects->catproj($item['catid'])
->result_array();
}
$this->load->view('vup_projects2', $data2);
then change your second view to
<?php foreach ( $cats as $item ) { ?> <!-- main divs -->
<div id="fragment-<?php echo $item['catid'];?>">
<ul>
<?php foreach ( $projects[$item['catid']] as $project )
{ ?>
<li>
<span><?php echo $project['projtit'];?></span></li>
<?php } ?>
</ul>
<?php foreach ( $projects[$item['cat_id']] as $project )
{ ?>
<div id="fragment-<?php echo $project['projid'];?>a" >
<?php echo $project['projtit'].' hooray';?>
</div>
<?php } ?>
</div> <!-- container -->
</div> <!-- YUI-UNIT-1-->
</div> <!-- YUI-GRID -->
</div> <!-- wrapper -->
So I took a closer look at what your trying to accomplish and I think I consolidated it into a single query and a single view. Maybe this will help
Controller:
class Projects extends CI_Controller {
function __construct(){
parent::__construct();
}
function projects() {
$cats = array(); // Unique cateogires
$projects = array(); // Projects that will go underneath
$this->load->model('msm_projects');
$query = $this->msm_projects->get_all();
// Make sure there are results
if ($query !== FALSE)
{
// Loop through once to find distinct categories for tabs
foreach ($query as $k => $v)
{
if ( ! array_key_exists($v['catid'], $tabs))
{
$tabs[$v['catid']] = $v['cat'];
}
}
// Loop through all of the results and group the items
// into arrays by their categories
foreach ($query as $k => $v)
{
$projects[$v['catid']][] = $v;
}
$data = array(
'cats' => $cats,
'projects' => $projects
);
$this->load->view('main', $data);
}
else
{
echo 'No results';
}
}
}
Model:
class Msm_projects extends CI_Model {
/* Returns everything you need */
function get_all()
{
$q = $this->db->select('c.catid, c.cat, p.projcat, p.projid, p.projtit')
->join('projects as p', 'c.catid = p.projcat', 'INNER')
->where('projpub = 1')
->order_by('c.catid')
->get('category as c');
if ($q->num_rows > 0)
{
return $q->result_array();
}
else
{
return FALSE;
}
}
}
View:
<div id="wrapper">
<div class="yui3-g">
<div class="yui3-u-1">
<div id="topbloc">
<img src="<?=base_url() /* Good not to hardcode url's if you can avoid it */;?>getop/base-images/topbloc.gif" width="800" height="50" align="middle" />
</div>
</div>
<div class="yui3-u-1">
<div id="navbloc">
<div id="linx">
<ul >
<li id="about"><?php echo anchor('cu_tya/about', 'about'); ?></li>
<li id="ourwork"><?php echo anchor('cu_projects/projects', 'projects'); ?></li>
<li id="contact"><?php echo anchor('cu_tya/contact', 'contact'); ?></li>
<li id="member"><?php echo anchor('cu_sites/pager', 'your page'); ?></li>
</ul>
</div>
</div>
</div>
<div class="yui3-u-1">
<div id="container">
<ul>
<?php foreach($cats as $id => $cat){ ?>
<li><span><?=$cat['cat'];?></span></li>
<?php } ?>
</ul>
<?php foreach ($cats as $id => $cat ) { ?> <!-- main divs -->
<div id="fragment-<?php echo $id;?>">
<ul>
<?php foreach($projects[$id] as $project){ ?>
<li>
<span><?php echo $project['projtit'];?></span>
</li>
<?php } ?>
</ul>
<?php foreach ($projects[$id] as $project) { ?>
<div id="fragment-<?php echo $project['projid'];?>a" >
<?php echo $project['projtit'].' hooray';?>
</div>
<?php } ?>
</div>
<?php } ?>
There are a lot of tricks to learn about optimizing the MVC process in CI, a lot of which I wish I learned earlier. Hopefully this helps some, let me know if you have questions. As for the pagination, try doing something similar to what i did in the foreach loop to get the main categories, and then subsequently pulling the pages out of the result array which are == to the category you're looking for.

Resources