简体   繁体   中英

Retrieving File Data in CodeIgniter by clicking on an anchor tag via AJAX

I have this question. How do i get a data from a file when an anchor is clicked,

this is my function in controller.

function change_log_year_view($year) {
    $file = $this->get_file($year);
    $message = $this->generate_message_body(read_file($file));


    if (!empty($year)) {
        $data['id'] = $this->session->userdata('id');
        $data['message'] = $message;
        $this->load->view('change_log_view', $data);
    }

This is the View.

        echo anchor('changelog/change_log_year_view/' . '2013', 'Change Log 2013');
        echo '|' . anchor('changelog/change_log_year_view/' . '2014', 'Change Log 2014');
        echo '|' . anchor('changelog/change_log_year_view/' . '2015', 'Change Log 2015');
        <text style="white-space: pre-line;"  id="message"><?php echo $message; ?></text>

This way worked. but is it possible if i use jquery or javascript?, if it is possible how does the script looks like, Thank You.

First of all change set default value of $year parameter to $year = '' to prevent getting error.

Basically your controller should echo out data, Not return. So echo $message out directly.

echo $this->generate_message_body(read_file($file));

PHP (Controller file) :

function change_log_year_view($year = '')
{
    if (empty($year)) {
        die('Optional Error Message...');
    }

    $file = $this->get_file($year);
    $message = $this->generate_message_body(read_file($file));

    // Is this necessary? I assume NO,
    // because you didn't show any usage of $id variable in your question.
    // $data['id'] = $this->session->userdata('id');

    // $data['message'] = $message;
    // $this->load->view('change_log_view', $data);

    echo $message;
}

Note:
The $this->get_file() and $this->generate_message_body() are OP's own method ( NOT CI core)

JS ( Using jQuery ) :

$.ajax({
    type     : 'GET',  // or 'POST', whatever you want.
    dataType : 'text', // output_value will be a plain text string.
    url      : 'YOUR_ANCHOR_TAG_URL',
    success  : function(output_value){
        // output_value is the result.
        // do what you want with it.
    }
});

Note:
Insert your controller URL address (do NOT forget the YEAR variable) instead of YOUR_ANCHOR_TAG_URL phrase.

You can get URLs automatically by $('your_link_selector').attr('href');

Just as a Demo:

Set class="ajax-call" to your <a> tags.

$('.ajax-call').on('click', function(e) {
    e.preventDefault();
    var _this = $(this);
    $.ajax({
        type     : 'GET',
        dataType : 'text',
        url      : _this.attr('href'),
        success  : function(output_value){
            // output_value is the result.
            // do what you want with it.
        }
    });
}

As a side-question: What is the <text> tag? A new generation of Markups? I didn't see this before, use <span> for inline element or <p> for block-level .

It can be done using jQuery ajax. You can call your controller method using ajax.

You can use Ajax in CI like this:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ajax with CI</title>
<script type='text/javascript' src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
    $('.ci_link').on('click',function(){
        // get link href string
        var linkHref = $(this).attr('href');
        // get year from string
        var getYearFromLinkHref = linkHref.split('/')[2];

        // your ajax param to send CI Controller
        var sendAjaxDataToController = {year:getYearFromLinkHref};

        // if you are using CSRF token in CI then
        // token name CI Function
        var csrftokenname = "<?php echo $this->security->get_csrf_token_name()?>";
        // token value CI Function
        var csrftokenvalue = "<?php echo $this->security->get_csrf_hash();?>";

        var sendAjaxDataToController = {year:getYearFromLinkHref,csrftokenname:csrftokenvalue};

        // Ajax Code Start
        $.ajax({
            type: "POST",           
            data: $.param(sendAjaxDataToController ),
            url: "http://www.yoursite.com/Changelog/change_log_year_view",          
            success: ajaxSucceess,
            error: ajaxError
        });
        // Ajax Code End

        // Code for Success Handler
        function ajaxSucceess(response) {
            console.log(response);
        }

        // Code for Error Handler
        function ajaxError(response) {
            console.log(response.status + ' ' + response.statusText);
        }
    }); 
});
</script>
</head>
<body></body>
</html>

// Your Controller Code

<?php
if (!defined('BASEPATH'))exit('No direct script access allowed');

class Changelog extends CI_Controller {

    /**
     * Chnage Log Year Function
     */
    function change_log_year_view() {
        // get year data from ajax post
        $year = $this->input->post('year');     
        $file = $this->get_file($year);
        $message = $this->generate_message_body(read_file($file));
        if (!empty($year)) {
            $data['id'] = $this->session->userdata('id');
            $data['message'] = $message;
            $this->load->view('change_log_view', $data);
        }

}
?>

// Your Anchor Code should like this:

<?php 
// create array attribute for link
$linkAttr = array('title'=>'your link title','class'=>'ci_link');
// show a link with attribute
echo anchor('changelog/change_log_year_view/2013', 'Change Log 2013', $linkAttr);
?>

// Your CI application/config/autoload.php

/*
| -------------------------------------------------------------------
|  Auto-load Helper Files
| -------------------------------------------------------------------
| Prototype:
|
|   $autoload['helper'] = array('url', 'file');
*/

$autoload['helper'] = array('url', 'form');

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