jQuery AJAX – How to Sort Response

ajaxjqueryresponsesort

I am showing ajax response in select options as below code. I want to sort the select options in alphabetical order of values.

Please provide a solution to sort below data on values basis.
My data is like {123:"green",124:"blue"}

function ajax_post(params, append_to, appent_type) {
            $.ajax({
                type: "GET",
                url: "<?= $this->getBaseUrl()?>" + "customcontroller/index/index/" + params,
                dataType: "json",
                success: function (data) {

                    if (append_to != 0) {
                        $(append_to).html('');
                        $(append_to).append('<option value="0">Select ' + appent_type + '</option>');
                        $.each(data, function (key, value) {

                            $(append_to).append('<option value="' + key + '">' + value + '</option>');
                        });
                    }
                }
            })
        }

Please provide a solution. I have tried to sort response in controller but when ajax loads it, it shows unsorted data.

Best Answer

You can try something like below.

function ajax_post(params, append_to, appent_type) {
    $.ajax({
        type: "GET",
        url: "<?= $this->getBaseUrl()?>" + "customcontroller/index/index/" + params,
        dataType: "json",
        success: function (data) {
            if (append_to != 0) {
                $(append_to).html('');
                $(append_to).append('<option value="0">Select ' + appent_type + '</option>');
                $.each(sortReponse(data), function (key, value) {
                    $(append_to).append('<option value="' + value.key + '">' + value.value + '</option>');
                });
            }
        }
    })
}

function sortReponse(data)
{
    var sorted = [];
    $(data).each(function(k, v) {
        for(var key in v) {
            sorted.push({key: key, value: v[key]})
        }
    });

    return sorted.sort(function(a, b){
        if (a.value < b.value) return -1;
        if (a.value > b.value) return 1;
        return 0;
    });
}

Try if that works.

Related Topic