douzhongjian0752 2013-09-02 15:53
浏览 33
已采纳

Jquery UI自动完成 - CodeIgniter - CSRF +模型+控制器

Updated answer with help from hackre, christian.thomas, olimortimer :

The problem : I wasn't filtering.

So how I solved it :

Jquery :

$(function() {
  var cct = $.cookie('ccn');
    $( "#searchscholarship" ).autocomplete({
      source: function(request, response) {
        $.ajax({
          url: '/global/c_ajax/ajax_scholarshipNames',
          type: "post",
          data: {term: request.term, 'ctn': cct},
          dataType: "json",
          success: function(data) {
            response( $.map( data.myData, function( item ) {
              return {
                label: item.scholName,
                value: item.scholID
              }
            }));
          }
        });
      },
      minLength: 3,
    });
  });

Big issue with AJAX and CI was the CSRF component, had to do some google searching on the "accepted" method of sending the token.

Then that sends to my c_ajax controller :

public function ajax_scholarshipNames() 
    {
        $this -> load -> model('m_ajax');
        $post = $this -> input -> post();
        $data = $this -> m_ajax -> scholarships($post);
        foreach ($data as $d) {
            $value['myData'][] = array(
                'scholID' => $d["intScholarshipID"],
                'scholName' => $d["txtScholarshipName"]
            );
        }
        $this -> output -> set_header('Content-Type: application/json; charset=utf-8');
        echo json_encode($value);
    }

Then in the model :

public function scholarships($post) // I usually don't use model just for database transactions but in this use case thats all I need the model to do. 
    {
        $name = '%' . $post["term"] . '%';
        $sql = "SELECT * FROM tableScholarship WHERE txtScholarshipName LIKE :name";
        $ajax_schol = $this -> db -> conn_id -> prepare($sql);
        $ajax_schol -> bindParam(":name", $name);
        $ajax_schol -> execute();

        return $ajax_schol -> fetchAll(PDO::FETCH_ASSOC);
    }

Again thank you!

ORIGINAL POST

I am trying to set up auto complete and for the most part I've done just fine, except now I am trying to tweak the remaining few issues with it.

Currently what is bothering me is that when I type for example "Scholarship" (which is a fake name of a scholarship in my DB) "fewfew" also appear (which is another name)

If I type S alone Scholarship should be the only thing that shows not "fewfew"

My Jquery :

$(function() { 
    $( "#searchscholarship" ).autocomplete({
      source: function(request, response) {
        $.ajax({
          url: '/global/c_ajax_controller/ajax_scholarshipNames',
          data: {term: request.term},
          dataType: "json",
          success: function(data) {
            response( $.map( data.myData, function( item ) {
              return {
                label: item.scholName, // Here it will either be Scholarship or fewfew
                value: item.scholID // 8 or 9
              }
            }));
          }
        });
      },
      minLength: 1,
    });
  });

my Php function in the ajax controller :

public function ajax_scholarshipNames() 
    {
        $data = $this -> m_global -> db_data($where = array(), $table = "tableScholarship");

        foreach ($data as $d) {
            $value['myData'][] = array(
                'scholID' => $d["intScholarshipID"],
                'scholName' => $d["txtScholarshipName"]
            );
        }
        $this -> output -> set_header('Content-Type: application/json; charset=utf-8');
        echo json_encode($value);        
    }

If it helps I am also using Codeigniter with CSRF turned ON however it doesn't seem to be affecting the outcome since the form I am using is using form_open :

<div id="editscholarship">
  <?php
    if (!$this -> session -> userdata('scholarshipID')) {
        echo form_open('/global/c_scholarshipmaintance/editscholarship/' . urlencode('1'));
        echo 'Please Enter Scholarship Name Below : <br>' . form_input('findScholarship', '', 'autocomplete="off", id="searchscholarship"');
    }
  ?>
</div>

Thanks for your time.

Edit :

A picture of the respone(s) I am getting

enter image description here

  • 写回答

1条回答 默认 最新

  • dqs86517 2013-09-02 16:02
    关注

    I don't think you're filtering the values that are coming back, as you're missing the options in your jQuery Ajax function which tells it what to filter on.

    See the example here - http://jqueryui.com/autocomplete/#remote-jsonp

          data: {
            featureClass: "P",
            style: "full",
            maxRows: 12,
            name_startsWith: request.term
          },
    

    However, I prefer to send the query to the PHP controller, and filter the values whilst running it against the database. This way, you're only sending back the values you require, and not all values and then filtering.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题