Reputation: 75
I have a JSON object generated from my CodeIgniter
function getListLotJSON($projectId){
$lotList = $this->reservationmodel->getListLot($projectId);
if($lotList){
$this->output
->set_content_type('application/json')
->set_output(json_encode($lotList));
}
else{
//do nothing
}
}
This returns:
[{"LotId":"3","LotName":"1"},{"LotId":"4","LotName":"2"}]
Then in my AJAX:
$(function(){
$("#ProjectName").change(function(){
var projectId = $("#ProjectName").val();
$.ajax({
async: false,
type: 'POST',
url: 'http://localhost:81/ORPS/reservation/getListLotJSON/' + projectId,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
error: function(result){
alert('No Available Lot!');
},
success: function(response){
$("#LotName").append($("<option>").val("").text("--Loading List of Lots Available--"));
var lotDetails = response;
console.log(lotDetails);
$("#LotName > option").remove();
$("LotName").append($("<option/>").val("").text("--Lot--"));
$("#LotName > option").remove();
$.each(lotDetails, function(){
$("#LotName").append('<option value='+lotDetails['LotId']+'>'+lotDetails['LotName']+'</option>');
});
}
});
});
});
I wanted to append LotName as the text in the and LotId as value. How do get the specific data to be displayed?
by the way, this is what console.log(lotDetails) gave: [Object { LotId="3", LotName="1"}, Object { LotId="4", LotName="2"}]
It just displays UNDEFINED in the .
Please help. Thanks much!
Upvotes: 0
Views: 1003
Reputation: 49919
Your for loop is not correct:
$.each(lotDetails, function(key, value){
$("#LotName").append('<option value='+value.LotId+'>'+value.LotName+'</option>');
});
You are accessing your main lotDetails array. Which does not have a property LotName. You need the items inside. So you loop, and in the function you have 2 arguments, the key (index in this case) and the value. The object inside.
Upvotes: 1
Reputation: 2119
In your each you are accessing the original array.
Try using something like this:
$.each(lotDetails, function(index, lotDetail){
$("#LotName").append('<option value='+lotDetail['LotId']+'>'+lotDetail['LotName']+'</option>');
});
I have passed the lotDetail argument to the each annonymus function. Now you can access each array element individually.
As you can see in the official jQuery documentation: http://api.jquery.com/jquery.each/
$.each([ 52, 97 ], function( index, value ) {
alert( index + ": " + value );
});
The first arugmentis the index and the second is the value.
Hope this helped. Let me know!
Cheers
Upvotes: 1