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.
chanchalchanchal
asked Nov 18, 2019 at 9:55
2 Answers 2
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.
answered Nov 19, 2019 at 10:03
Try below code.
$finalModel=array_combine(array_values($modelValues),array_values($modelNames));
asort($finalModel);
$result = json_encode($finalModel);
return $result;
answered Nov 18, 2019 at 10:41
-
This gives error - syntax error, unexpected 'asort' (T_STRING) in line asort($finalModel);chanchal– chanchal2019年11月18日 10:49:30 +00:00Commented Nov 18, 2019 at 10:49
-
check your code if you forget
;in first line.Rakesh Varma– Rakesh Varma2019年11月18日 10:53:19 +00:00Commented Nov 18, 2019 at 10:53 -
I have fixed there was some extra content but it runs as before without sorting anything.chanchal– chanchal2019年11月18日 10:56:33 +00:00Commented Nov 18, 2019 at 10:56
-
can you post your controller code and some value of
$modelValuesand$modelNamesRakesh Varma– Rakesh Varma2019年11月18日 11:01:18 +00:00Commented Nov 18, 2019 at 11:01 -
asort was not working, so I used sort. It did the work . Thanks for help.chanchal– chanchal2019年11月18日 11:02:31 +00:00Commented Nov 18, 2019 at 11:02
default
asort()in your controller.