Search code examples
jqueryajaxcodeigniter-3

How do I post the data from select2 plugin using ajax?


I try to post the data from select2 but it's not working at all any one have any idea?

By the way I'm using the code igniter 3 for my framework.

My code

$('#reference').change(function(){
   var ref = $(this).val();
   $.ajax({
      type: 'POST',
      url: '<?= base_url('/user/getItem')?>',
      data: {
         ref: ref
      },
      dataType: 'JSON',
      success: function(data){
            console.log('anything');
         }
      })
});

html

<select multiple="multiple" id="reference" name="reference[]">
   <?php foreach($ref as $r):>
      <option value="<?= $r['id']?>"><?= $r['name']?></option>
   <?php endforeach;>
</select>

I also tried this code but also not work

 $('#reference').select2({
            closeOnSelect: true,
            placeholder: "Select Reference",
            
            ajax: {
                type: 'POST',
                url: '<?= base_url('/user/getItem')?>',
                data: {
                    ref: $(this).val()
                },
                dataType: 'JSON',
                success: function(data){
                    console.log('anything');
                }
            }
        });

Solution

  • Try to change "type" to "method"

    $('#reference').change(function(){
      var ref = $(this).val();
      $.ajax({
          method: 'POST',
          url: '<?= base_url('/user/getItem')?>',
          data: {
             ref: ref
          },
          dataType: 'JSON',
          success: function(data){
              console.log('anything');
          }
      })
    });