Reputation: 891
I have an ASMX web service that is successfully responding with the following JSON:
[{
"Id": 49,
"SupplierName": "Supplier 1"
}, {
"Id": 50,
"SupplierName": "Supplier 2"
}, {
"Id": 51,
"SupplierName": "Supplier 3"
}, {
"Id": 52,
"SupplierName": "Supplier 4"
}]
I am trying to get my ajax call to loop through this array and append the results to a select control in my form. Unfortunately, I am fairly new to using ajax and have not been able to accomplish this yet. Any guidance would be helpful.
$.ajax({
type: "POST",
url: "/StockPileDelivery.asmx/PopulateSupplierDdl",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = $.parseJSON(msg.d);
$.each(data, function (i, item) {
alert(i);
// $("#dropDownCars").append("<option>" + value.carsName + "</option>");
});
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
});
UPDATE Below is my revised AJAX which is returning an error stating "Cannot use 'in' operator to search for '158' in
$.ajax({
type: "POST",
url: "/StockPileDelivery.asmx/PopulateSupplierDdl",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var data = msg.d;
$.each(data, function (i, item) {
alert(item.Id);
//$("#Suppliers").append("<option value='" + item.Id + "'>" + item.SupplierName + "</option>");
});
},
error: function (xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message);
},
});
Upvotes: 0
Views: 3160
Reputation: 1992
The data already is an object here, that's why I didn't do the parseJSON method. Here is a working fiddle:
var msg = [{
"Id": 49,
"SupplierName": "Supplier 1"
}, {
"Id": 50,
"SupplierName": "Supplier 2"
}, {
"Id": 51,
"SupplierName": "Supplier 3"
}, {
"Id": 52,
"SupplierName": "Supplier 4"
}];
$(function(){
$.each(msg, function (i, item) {
$("#dropDownCars").append("<option value='"+item.Id+"'>" + item.SupplierName + "</option>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropDownCars">
</select>
Upvotes: 2
Reputation: 453
On the face of it your ajax looks ok
Have a look at the $.each documentation - http://api.jquery.com/jquery.each/
i
in your function is the index, item is the actual value.
alert(item)
(or better yet console.log(item)
) would confirm this.
You probably then want something like
$("#dropDownCars").append("<option>" + item.SupplierName+ "</option>");
Upvotes: 0