Home > OS >  Loading Select2 statement data with onclick AJAX call
Loading Select2 statement data with onclick AJAX call

Time:11-10

Currently I'm using a controller to fetch all my data and placing it in a foreach statement in my view class. So whenever the page is loaded, it executes this function. To achieve this I used something like this:

Controller Class:

$add['sources']= $this->contacts_model->get_array();

View class:

<select name="contact_source" id="contact_source" class="form-control select2 <?php echo form_error('contact_source') ? 'red' : '' ?>" required/>          
          <option value="">Select</option>
          <?php foreach($sources as $source): ?>
          <option value="<?php echo $source['id']; ?>" <?php echo ($this->input->post('contact_source') == $source['id'])?'selected="selected"':''?>><?php echo $source['title']; ?></option>
          <?php endforeach; ?>
   </select>

But now I want the page to load faster, so for that I want to load the dropdown only when the user has clicked on that particular select2 statement. I've tried the following code to get the select2 variables with the select 2 functionality of getting an input text with dropdown, but none of them work. It just brings up a normal dropdown that loads when my page loads.

View Class:

<select name="contact_source" id="contact_source" class="form-control select2 <?php echo form_error('contact_source') ? 'red' : '' ?>" required/>          
              <option value="">Select</option>
              <?php foreach($sources as $source): ?>
              <option value="<?php echo $source['id']; ?>" <?php echo ($this->input->post('contact_source') == $source['id'])?'selected="selected"':''?>><?php echo $source['title']; ?></option>
              <?php endforeach; ?>
</select>

$(document).ready(function(){
  $('#contact_source').on('click', function(e) {
    $("#contact_source").select2({
      minimumInputLength: 2,
      tags: [],
      ajax: {
          url: "<?php echo site_url('contacts/add'); ?>/",
          dataType: 'json',
          type: "GET",
          delay : 50,
          data: function (data) {
              return {
                sources: data.sources
              };
          },
          results: function (data) {
              return {
                  results: $.map(data, function (item) {
                      return {
                          text: item.sources,
                          id: item.id
                      }
                  })
              };
          }
      }
  });
})
});

CodePudding user response:

Remove select2 in <select name="contact_source" id="contact_source" required/>

and remove also $('#contact_source').on('click', function(e) {

And I recommend jQuery Autocomplete. https://jqueryui.com/autocomplete/#remote

  • Related