简体   繁体   中英

jQuery Select2 JSON data

My script won't load any data in the Select2. I made a test.php with JSON data (which will be provided external after everything works. (test.php is my internal test)).

Output of test.php

[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]

jQuery script:

$("#billing_postcode_gemeente").select2({
    minimumInputLength: 2,
    tags: [],
    ajax: {
        url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (data) {
            alert(data);
        },
        processResults: function(data) {
            return {
                results: $.map(data.suggestions, function(obj) {
                    return {
                        id: obj.key, text: obj.value
                    }
                })
            };
        }
    }
});

I have been searching and checking all other solutions. It it not working for me. I'm stuck.

Update: jQuery script so far

    $("#billing_postcode_gemeente").select2({
    minimumInputLength: 2,
    placeholder: "Voer uw postcode in..",
    ajax: {
        url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (data) {
            return {
            ajax_call: 'addressZipcodeCheck_BE',
            zipcode: '1200'
            };
        },
          processResults: function(data) {
              alert(data);
              correctedData = JSON.parse(data)[0]suggestions;
              alert(correctedData);
                return {
                  results: $.map(correctedData, function(obj) {
                    return {
                      id: obj.key,
                      text: obj.value
                    }
                  })
                };
        }
    }
});

Here is a working fiddle for your example. I have done if on a local JSON object but you can replicate the same results on your response or maybe change your response accordingly.

Your data.suggestions is nothing. Because data is a JSON array whose first element is a JSON object with key suggestions and value an array of suggestions.

Run this code in your JQuery enabled browser console and you will undestand.

var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;

Also check this answer to see how a proper response should look like.

Updated answer: Sending additional data to back-end:

$('#billing_postcode_gemeente').DataTable(
{
 ......
                    "processing" : true,
                    "serverSide" : true,
                    "ajax" : {
                        url : url,
                        dataType : 'json',
                        cache : false,
                        type : 'GET',
                        data : function(d) {
                            // Retrieve dynamic parameters
                            var dt_params = $('#billing_postcode_gemeente').data(
                                    'dt_params');
                            // Add dynamic parameters to the data object sent to the server
                            if (dt_params) {
                                $.extend(d, dt_params);
                            }
                        }
                    },
});

Here dt_params is your additional parameter (the zipcode that you wish to send to the server to get an appropriate response). This dt_params gets added to the datatable parameters and can be accessed in your back-end to appropriate the response.

There must be a place where you are taking the zipcode entry. On the listener of that input box you can add the below code to destroy and recreate the datatable to reflect the changes. This code will add key-value (key being zip_code ) pair to the dt_params key in your request JSON:

function filterDatatableByZipCode() {

        $('#billing_postcode_gemeente').data('dt_params', {
            ajax_call: 'addressZipcodeCheck_BE',
            zip_code : $('#some_imput_box').val()
        });
        $('#billing_postcode_gemeente').DataTable().destroy();
        initDatatable();
    }

Try this way

$(".js-data-example-ajax").select2({
    ajax: {
         url: "https://api.github.com/search/repositories",
         dataType: 'json',
         delay: 250,
         data: function (params) {
           return {
              q: params.term, // search term
              page: params.page
           };
        },
        processResults: function (data, page) {
            // parse the results into the format expected by Select2.
            // since we are using custom formatting functions we do not need to
            // alter the remote JSON data
           return data.items;
        },
        cache: true
   },
   minimumInputLength: 1,
   templateResult: formatRepo, // omitted for brevity, see the source of this page
   templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

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