Xariez Xariez - 22 days ago 5
jQuery Question

Filtering an AJAX request call

I have an issue related to a filtered AJAX call I am making to populate a list with ZipCodes and Regions.

My JSON array that I take in from

ZipCodeService.ashx
contains the fields "Name" and "Code" and I am trying to only get the results that has "SampleCity" in the Name field. However, right now all of the fields and their data are getting returned, so the filter is obviously not working as it should or like I am expecting it to. Any help is much appreciated!

I am new to JQuery/Javascript and extremely new to AJAX, so bear with me.

site.js

$.ajax({
async: true,
contentType: 'application/json; charset=utf-8',
method: "POST",
url: "../ZipCodeService.ashx",
data: { Name: "SampleCity" },
success: function (data) {

var $select = $('#list1');
$.each(data, function (i, item) {
$('<option>',
{
value: item.Code + " - " + item.Name,
}).html(item.Code + " - " + item.Name).appendTo($select),
'</option>';
});

}
});


ZipCodeService.ashx

public class ZipCodeService : IHttpHandler
{
[DataContract]
public class ZipCode
{
[DataMember]
public string Code { get; set; }

[DataMember]
public string Name { get; set; }
}

public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";

var p = new ZipCode[] {
new ZipCode()
{
Code = "00001",
Name = "SampleCity"
},new ZipCode()
{
Code = "00002",
Name = "SampleCity2"
},new ZipCode()
{
Code = "00003",
Name = "SampleCity3"
},new ZipCode()
{
Code = "00004",
Name = "SampleCity4"
}
};

MemoryStream stream1 = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ZipCode[]));
ser.WriteObject(stream1, p);

context.Response.Write(Encoding.UTF8.GetString(stream1.ToArray()));
}

}

Answer

I think you can use the if condition for that :

$.ajax({
    async: true,
    contentType: 'application/json; charset=utf-8',
    method: "POST",
    url: "../ZipCodeService.ashx",
    data: {
        Name: "SampleCity"
    },
    success: function(data) {
        var $select = $('#list1');
        $.each(data, function(i, item) {
            if (Item.Name == "SampleCity") {
                $select.append('<option value="' + item.Code + '">' + item.Name + '</option>');
            }
        });
    }
});