简体   繁体   中英

CodeIgniter - Using database connection with AJAX request

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM