0

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()));
    }

}
9
  • 2
    I don't see a "filter" in this code. You are just appending all of the results to #list1
    – Turnip
    Nov 18, 2016 at 13:01
  • I am, without any doubt a beginner to AJAX and Jquery so I'd personally be expecting the data: {} attribute to be the filter. I guess this is not the case? @Turnip
    – Xariez
    Nov 18, 2016 at 13:03
  • 1
    Can you add the code of ZipCodeService.ashx? You are sending a JSON object to the page as a parameter. If the .ashx page is expecting it everything should work ok, if it's not the case, maybe you should send something different.
    – Bardo
    Nov 18, 2016 at 13:04
  • Shouldn't the filtering happen on server side, ie. in ZipCodeService.ashx which you are posting to? You should take parameter Name and filter by it's value.
    – Esko
    Nov 18, 2016 at 13:05
  • You need to show us the contents of ZipCodeService.ashx. This doesn't really have anything to do with ajax or the code you have posted
    – Turnip
    Nov 18, 2016 at 13:05

2 Answers 2

1

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>');
            }
        });
    }
});
2
  • Just got it fixed myself this way as well! I'll mark this as the answer as it is indeed the code that got it fixed.
    – Xariez
    Nov 18, 2016 at 13:14
  • @Xariez Don't you want the filter happening on server side instead of client side?
    – Aruna
    Nov 18, 2016 at 13:24
0

If you want to do the filtering in client side, you can try Surjeet's solution.

But if you need to do the same in server side as you already sent a input data, you can try the below.

I have used JavaScriptSerializer to serialize the incoming data and you can add a namespace for this System.Web.Script.Serialization with the reference to the assembly System.Web.Extensions.dll.

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

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

    [Serializable]
    public class Zip
    {
       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"
        }
        };

        var sr = new StreamReader(context.Request.InputStream);
        var stream = sr.ReadToEnd();    
        var serializer = new JavaScriptSerializer();
        var postedData = serializer.Deserialize<Zip>(stream); 

        var filtered = p.Where(z => z.Name == postedData.Name).ToArray(); 

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

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

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.