yulianto saparudin yulianto saparudin - 4 months ago 9
Ajax Question

How to get select2 data from ajax response

I don't know what the title should be, hehe
but anyone know how to get select2 data from ajax response

here my code:

function selectData(){
$('#select-data').select2({
tags: true,
data: arr_data,
});
}


var arr_data = dataArr();

function dataArr(){
$.ajax({
url: SITE_URL + 'position/allowance_get',
dataType: 'json',
});

}


I don't know why it doesn't work, haha

the response like this

[{"allowance_id":"1","position_id":"1","allowance_name":"Tunjangan Kendaraan","allowance_value":"1000000"
},{"allowance_id":"10","position_id":"4","allowance_name":"Tunjangan Istri Tua","allowance_value":"1000000"
},{"allowance_id":"11","position_id":"4","allowance_name":"Tunjangan Istri Muda","allowance_value":"1000000"
},{"allowance_id":"29","position_id":"10","allowance_name":"Allowance Lipstic","allowance_value":"500000"
},{"allowance_id":"30","position_id":"10","allowance_name":"Allowance Powder","allowance_value":"600000"
},{"allowance_id":"31","position_id":"10","allowance_name":"Allowance Dalaman","allowance_value":"1000000"
},{"allowance_id":"32","position_id":"11","allowance_name":"Allowance Tunjangan","allowance_value":"20000000"
},{"allowance_id":"33","position_id":"11","allowance_name":"Allowance Kendaraan","allowance_value":"5000000"
},{"allowance_id":"34","position_id":"12","allowance_name":"Tunjangan Keluarga","allowance_value":"1000000"
},{"allowance_id":"35","position_id":"12","allowance_name":"Tunjangan Transportasi","allowance_value"
:"2000000"},{"allowance_id":"36","position_id":"12","allowance_name":"Tunjangan Hari Raya","allowance_value"
:"10000000"},{"allowance_id":"39","position_id":"13","allowance_name":"Tunjangan Makan","allowance_value"
:"2000000"},{"allowance_id":"40","position_id":"13","allowance_name":"Tunjangan Minum","allowance_value"
:"400000"},{"allowance_id":"41","position_id":"15","allowance_name":"Tunjangan Dinas","allowance_value"
:"23234343434"}]


I want to get the allowance_id and allowance_name

Answer

Go with below code flow

var arr_data = [];

function selectData(){
    $('#select-data').select2({
      tags: true,
      data: arr_data,
    });
}

function dataArr(){
  $.ajax({
    url: SITE_URL + 'position/allowance_get',
    dataType: 'json',
    success : function(data) {
      var tempObj = {};
      for(var i = 0; i < data.length; i++){
        tempObj = {"id":data[i].allowance_id,"text":data[i].allowance_name};
        arr_data.push(tempObj);
      }
      selectData();

    }
  });

}
Comments