Select2 with Ajax + PHP

9.6k views Asked by At

I am trying to use select2 pulling data using ajax from php back end. I could not figure out the documentation as much as I would like to. I think i probably missed some taken for granted stuffs. Please can you help with a simple example. I started or like this...

html

<select id="select_proj" style="width:10em">
  <option value="" selected="selected">Search</option>
</select>

js

$('select').select2();
        $("#select_proj").select2({
          ajax: {
              url: '../app/select_prj.php',
            dataType: 'json',
            delay: 250,
            data: function (term, page) {
              return {
                  select_proj: term, // search term
                  page: 10
              };
            },
            processResults: function (data, page) {
              return {
                results: data.items
              };
            },
            cache: true
          },
          escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
          minimumInputLength: 1,
        });

In php

    $data_wildcardsearch = $_POST['term'];

is throwing error

[Notice: Undefined index: term in b>-----/app/select_prj.php on line 18
]

Could you please help? Can you please share a sample code as well?

2

There are 2 answers

2
Tool On BEST ANSWER

In data() function you must pass 'term' as a key instead of select_proj.

$('select').select2();
        $("#select_proj").select2({
          ajax: {
              url: '../app/select_prj.php',
            dataType: 'json',
            delay: 250,
            data: function (term, page) {
              return {
                  term: term, // search term
                  page: 10
              };
            },
            processResults: function (data, page) {
              return {
                results: data.items
              };
            },
            cache: true
          },
          escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
          minimumInputLength: 1,
        });

Then you can get it by:

$data_wildcardsearch = $_POST['term']; 
0
KTAnj On

You have post term with key => 'select_proj'. Change code as below,

$data_wildcardsearch = $_POST['select_proj'];

OR

data: {term: term, page: 10},