I'm tyring to use AJAX to populate a dropdown box based on the selection of another dropdown. I followed a tutorial using jQuery located here - http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/ and have altered the select box ID names in the select box names in the script.
When there's a change to the value of the main checkbox the ajax is sent and returns as below:
{"1":"Kieran Hutchinson","2":"Caleb Tan","3":""}
THis is slightly different to the JSON string that is returned in the tutorials code which looks like this
[{optionValue:10, optionDisplay: 'Remy'}, {optionValue:11, optionDisplay: 'Arif'}, {optionValue:12, optionDisplay: 'JC'}]
I'm thinking this is the issue but I have no idea how to get the correct values out of my JSON response.
The javascript is as below:
$(function(){
$("select#ContactCompanyId").change(function(){
$.getJSON("contactList",{id: $(this).val(), ajax: 'true'}, function(j){
var options = '';
for (var i = 0; i < j.length; i++) {
options += '<option value="' + j[i].optionValue + '">' + j[i].optionDisplay + '</option>';
}
$("select#QuoteContactId").html(options);
})
})
})
Thanks in advance
If an array does not start with a
0
index, it is converted into a JSON Object with keys and values instead of an Array. Just use$.each
to loop through, grabbing the key (i.e.1
) and the value (i.e.Kieran Hutchinson
):Since JSON can be considered as associative array also, you may do smth like this:
More info about JSON can be found in this article - "Mastering JSON"
Your problem is this line:
is expecting data sent in the format of the tutorial. Yours is a different format. Try:
You have the 'value' as just an index -- i, and the value as the value with that key, j[i]. so the option tag you'd end up with would look like this:
To explain more: the original data was in format like this:
also, if that was actual data returned in your example, your iterator
for (var i = 0; i < j.length; i++)
will fail because you aren't starting at an index of 0. Usefor(i in j) { ... }
If you could slightly change your response to return value and text keys in JSON:
you could use JQuery view engine and just load the array into a dropdown:
See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown