简体   繁体   中英

Get data from select2 plugin to ajax

I have multiple select fields with multiple select, implemented with select2 latest plugin. I want to send selected data with ajax to the Laravel controller. how can I do this? In the preview section of the browser network tab shows "No properties".

I wrote these codes to a submit button to submit selected services from select2 field.

$('#submit-service').click(function(e){
  e.preventDefault();
  var values = $('.service-select').select2().val();
    $.ajax({
        type:'POST',
        url: '/process_services',
        data: values,
        success: function(data) {
          console.log(data);
        }
    })
});

Laravel Controller,

class ServiceController extends Controller
 {
     public function storeServices(Request $request)
     {   
          $services = $request->all();
          return $services;
     }
 }

Route,

Route::post('/process_services', 'ServiceController@storeServices');
$("#submit-service").select2({
  e.preventDefault();
  var values = $('.service-select').select2().val();
   $.ajax({
        type:'GET',
        url: '/process_services',
        data: values,
        success: function(data) {
          console.log(data);
        }
    })
});

You have to change your ajax code.

$('#submit-service').click(function(e){
e.preventDefault();
$(".service-select").select2({
    ajax: {
        type:'POST',
        url: '/process_services',
        dataType: 'json',
        delay: 250,
        data: function (params) {
            return {
              values: params.term // search term
            };
        },
        processResults: function (response) {
            console.log(response);
            return {
               results: response
            };
        },
        cache: true
    }
});
});

Get the entered values using params.term in data. The successful callback handle by processResults function where initialize results with the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM