CodeIgniter - Using database connection with AJAX request - php

I'm using a script (applications/view/pages/home.php) which has an AJAX request whereby it gets and displays the content of another script (we'll call it scheduler.php). The scheduler file is just a file containing dynamically modified html based on a $_GET parameter passed to it from the AJAX request.
My issue is that this dynamic content comes from the database, and since the scheduler.php is being called by AJAX, it doesn't inherit the $this->db-> ability.
I get the error: Fatal error: Using $this when not in object context.
How can I fix this? I am a novice to both CodeIgniter and to AJAX. Thanks!
Edit: Scheduler.php code:
<?php
$shift = $_GET['shift'];
?>
<table>
<tr>
<th><?php echo $d->format('l') . '<br>' . $d->format('F jS'); ?></th>
</tr>
<tr>
<td>
<?php
$this->db->select('id', 'event', 'time');
$query = $this->db->get('myTable', $shift, $shift-5);
foreach ($query->result() as $row) {
echo "<a href='/schedule/{$row['id']}'>{$row['event']} at {$row['time']}</a><br>";
}
</td>
</tr>
</table>

As per discussion in comments, scheduler.php is not controller or library.
So you are calling outside the CI project. You can't use CI DB function untill you process through CI index.php file.
So just make scheduler.php as controller as below:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Scheduler extends CI_Controller {
public function index($shift = "")
{
// add your stuff here to response to ajax request.
}
}
?>
Then change ajax url to : domain.com/index.php/scheduler/index/{shift_value_here}

You can get access to the CodeIgniter "super object" through $CI =& get_instance();
After that, replace $this with $CI in scheduler.php and you will have access to the framework libraries and functions etc.
Read section: Utilizing CodeIgniter Resources within Your Library in the documentation.

Related

How do you call a helper function in the category.tpl file OpenCart 2

This is my previous question: How to convert a decimal $attribute['text']; into a fraction in opencart
I have a helper function that is declared in startup.php and defined in helper/dec2frac.php
I am trying to call the helper function from a category.tpl file with this code:
<?php if ($product['attribute_groups']) { ?>
<?php foreach ($product['attribute_groups'] as $attribute_group) { ?>
<?php foreach ($attribute_group['attribute'] as $attribute) { ?>
<?php /*var_dump($attribute);*/
if($attribute['name'] == "Adjuster Position")
{
//echo("<h1>HELLLO</h1>");
dec2frac($attribute['text']);
}
?>
...but I am getting this error message:
Fatal error: Call to undefined function dec2frac() in startup.php
helper/dec2frac.php
How can I call my helper function in the category.tpl file?
Do I need to reference the helper function in my category.php file?
I am trying to achieve same but in a different way. This following link will help, it will work with opencart v2.3x
Not able to find my custom object in Registry - OpenCart-v2.3.0.2
Try the above link (it is my posted question). Create a object and save it in registry and get it from registry and call the required function.
in your category.php file, get your object from registry. For eg:
$kt = $registry->get('ktLibrary'); //Object
$value = $kt->getSomeValue(); //function
object $kt will be available throughout the category.tpl file.

Codeigniter fatal error using $this

Using Codeigniter 2.2.1
I am attempting to parse an RSS feed using this example:
http://hasokeric.github.io/codeigniter-rssparser/
I have downloaded the library and added to my libraries folder.
I then added this code to my view:
function get_ars()
{
// Load RSS Parser
$this->load->library('rssparser');
// Get 6 items from arstechnica
$rss = $this->rssparser->set_feed_url('http://feeds.arstechnica.com/arstechnica/index/')->set_cache_life(30)->getFeed(6);
foreach ($rss as $item)
{
echo $item['title'];
echo $item['description'];
}
}
When I call the function get_ars(); I get the following error:
Fatal error: Using $this when not in object context in C:\wamp\www\xxxx\application\views\pagetop_view.php on line 8
I had a look at this post, but it didn't solve my issue.
Can someone please tell me what I am doing wrong
Don't directly include the function code in the view.
Create a helper function and then use it inside your view. For instance,
1) helpers/xyz_helper.php
function get_ars()
{
$ci =& get_instance();
// Load RSS Parser
$ci->load->library('rssparser');
// Get 6 items from arstechnica
$rss = $ci->rssparser->set_feed_url('http://feeds.arstechnica.com/arstechnica/index/')->set_cache_life(30)->getFeed(6);
foreach ($rss as $item)
{
echo $item['title'];
echo $item['description'];
}
}
2) Load the helper in your autoload file (config/autoload.php)
$autoload['helper'] = array('xyz_helper');
3) Now you can use it in view
<?php
$ars = get_ars();
foreach($ars as $a) {
?>
...
...
<?php } ?>
Read the docs:
Helper
Creating Libraries
try this
$CI =& get_instance();
and after this use $CI instead of $this.
CodeIgniter is a MVC framework. It implies that uou shouldn't be trying to load stuff or write function inside your views.
However you can call functions inside your view. Those function must be written inside an helper.
See this for more detail : http://www.codeigniter.com/user_guide/general/helpers.html
EDIT : See Parag Tyagi's answer for the helper solution
Also, in your case you should be able to achieve what you need just by passing vars from your controller to your view.
I suppose here that your view is loaded inside your index() and your is named "myview".
Controller :
public function index()
{
// Load RSS Parser
$ci->load->library('rssparser');
$data["rss"] = $ci->rssparser->set_feed_url('http://feeds.arstechnica.com/arstechnica/index/')->set_cache_life(30)->getFeed(6);
$this->load->view("myview", $data);
}
View :
<?php
foreach ($rss as $item)
{
echo $item['title'];
echo $item['description'];
}
?>

PHP : Can not call object method from a page which included by another method of my class

I have just created a class to control my php application, and I have one big problem ( I use 2 days for thinking and searching about it but can't find any solutions). My class contains a method named register(), which load scripts into pages. My class is:
class Apps
{
protected $_remember; // remember something
public function register($appName)
{
include "$appName.php"; //include this php script into other pages
}
public function set($value)
{
$this->_remember = $value; // try to save something
}
public function watch()
{
return $this->_remember; // return what I saved
}
}
And in time.php file
$time = 'haha';
$apps->set($time);
As the title of my question , when I purely include time.php into main.php, I can use $apps->set($time) ($apps has been defined in main.php). Like this main.php:
$apps = new Apps();// create Apps object
include "time.php";
echo $apps->watch(); // **this successfully outputs 'haha'**
But when I call method register() from Apps class to include time.php , I got errors undefined variable $apps and call set method from none object for time.php (sounds like it doesn't accept $apps inside time.php to me) . My main.php is:
$apps = new Apps();// create Apps object
$apps->register('time'); // this simply include time.php into page and it has
//included but time.php doesn't accept $apps from main.php
echo $apps->watch(); // **this outputs errors as I said**
By the way , I'm not good at writing . So if you don't understand anything just ask me. I appreciate any replies. :D
If you want your second code snippet to work, replace the content of time.php with:
$time = 'haha';
$this->set($time); // instead of $apps->set($time);
since this code is included by an instance method of the Apps class, it will have access to the instance itself, $this.

Passing further inside of template

I'm using the same template library that phil sturgeon created and I have the following layout for my control panel. I am getting this error. I ran a var_dump on the template variable inside the control panel controller and it showed the string of the control panel view but when I do the same thing inside of the content view it says there was no body index. I would like to know how I can pass the data to the content view.
Any ideas for me?
Severity: Notice
Message: Undefined index: body
Filename: partials/content.php
Line Number: 8
Control Panel Controller
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Controlpanel extends Backend_Controller
{
public function __construct()
{
parent::__construct();
}
public function index()
{
$this->template
->title('Control Panel')
->set_layout('controlpanel')
->set_partial('header', 'partials/header')
->set_partial('sidebar', 'partials/sidebar')
->set_partial('breadcrumbs', 'partials/breadcrumbs')
->set_partial('content', 'partials/content')
->set('user_data', $this->users_model->get($this->session->userdata('uid')))
->build('dashboard');
}
}
content.php
<div id="content">
<!-- Insert Header -->
<?php echo $template['partials']['breadcrumbs']; ?>
<div class="separator bottom"></div>
<?php echo $template['body']; ?>
</div>
I've tried looking into this and still haven't found a solution. I was hoping someone else might see something I am not.
I use his library too, and got some ploblems when passing objects through
$this->template->set('data_name', $my_object);
just cast it to array.
$this->template->set('data_name', (array) $my_object);
THe following works for me:
$this->template->set('body', $body);
Then in my view (using the PyroCMS lex parser):
{{ body }}
Alternatively, you could assign an array to the set method:
// $page is from a db query
$this->template->set('page', $page);
Then in the view:
{{ page->body }}

Best way for scripts in codeigniter

In CodeIgniter I often have many scripts inherent to my project, for instance:
<?php
// Load many things
$this->load->model('news_model');
$this->load->helper('utility_helper');
$news = $this->news_model->get_basic_news();
// For moment no news
$view_datas['news']['check'] = false;
if ($news) {
$view_datas['news'] = array(
'check' => true,
'news' => _humanize_news($news)
);
}
?>
This script is used in different controllers, at the moment I create a scripts folder and I import it like that: include(APPPATH . 'scripts/last_news.php'); I'm quite sure it's not the best way to handle this problem. Any thoughts on that?
Update:
A solution given in the answers is to use a helper or a library.
Let's imagine a rewrite of my previous code:
class Scripts {
public function last_news() {
// Load many things to use
$CI =& get_instance();
$CI->load->model('news_model');
$CI->load->model('utility_helper');
$news = $CI->news_model->get_basic_news();
// Avoid the rest of code
}
}
Just create a new library and load that library whereever you require?
e.g.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Newclass {
public function get_news($limit)
{
//return news
}
}
/* End of file Newsclass.php */
In your controllers
$this->load->library('newsclass');
$this->newsclass->get_news($limit);
Or another idea is to create helper functions.

Categories