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.

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

报告相同问题?

悬赏问题

  • ¥50 易语言把MYSQL数据库中的数据添加至组合框
  • ¥20 求数据集和代码#有偿答复
  • ¥15 关于下拉菜单选项关联的问题
  • ¥20 java-OJ-健康体检
  • ¥15 rs485的上拉下拉,不会对a-b<-200mv有影响吗,就是接受时,对判断逻辑0有影响吗
  • ¥15 使用phpstudy在云服务器上搭建个人网站
  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况