Bind a CheckBox list from database using jQuery AJAX

Hi All,

I have seen many questions in the forums that how can we bind the CheckBox list from the database via Ajax. There could be many ways to do in an ASP.NET but I will be using the one of the most efficient options available .

In this post, I’ll be using jQuery Ajax to get the data from the server (that will be fetch the data from database) and then will create the CheckBox list dynamically.

Continue reading

Advertisements

Accessing other domain web services via jQuery Ajax (CORS)

Now a days, most of the web developers are working on mainly Client side programming to make the web more responsive, intuitive and user friendly. So avoiding the code behind, accessing the server via Ajax, passing and getting the data in JSON format, generating the DOM elements at Client side etc becoming very common these days and these all prepared the ground for many Client side libraries to come up and that’s what we are seeing now a days.

One of the most popular Client side library, jQuery, provides a lot of wrapper methods for writing quick and easy Client side code. You guys must have used jQuery ajax to initiate a ajax call and passing data to and fro in JSON format. As you must be knowing that XMLHTTPRequest  is the base for all Client side ajax call. All the Client side libraries provides a wrapper over it for making any AJAX call. So I’ll start with an example

I have created an empty web application and added a web page . I also added a jQuery script file. I created one small web method GetRatingValues at code behind that returns a list of numbers (Gave a name called rating). So let’s see the code and get it running

So my aspx code is like

<form id="form1">
<div><input onclick="GetRatingData()" type="button" value="GetRatings" />
<div id="ratingDetails" style="display: none;">
<h1>Available Rating Values</h1>
<div id="ratingValues"></div>
</div>
</div>
</form>

And my javascript code is like

<script type="text/javascript" language="javascript">// <![CDATA[
        function GetRatingData() {
            GetRatingValues();
        }
        function AjaxSucceeded(result) {
            $("#ratingDetails").show();
            $("#ratingValues").html(result.d);
        }
        function AjaxFailed(result) {
            alert('Failed to load');
        }

        function GetRatingValues() {
            $.ajax({
                type: "Post",
                url: "First.aspx/GetRatingValues",
                contentType: "application/json; charset=utf-8",
                data: '',
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });
        }

// ]]></script>

And my web method at code behind is as

 [WebMethod()]
    public static string GetRatingValues()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        IList ratingList = new List() { "5", "4", "3", "2", "1" };
        string str = ser.Serialize(ratingList);
        return str;
    }

Now if you run the code and Click on the button. It’ll run perfectly fine and page will be displayed as

SamedomainAjaxCall

Now let’s have another scenario. I have added a simple HTML page (Test.html) in my solution and I have added the following script on my aspx page

 function GetHTML() {
            $.ajax({
                type: "GET",
                url: "Test.html",
                success: ShowHTML,
                error: AjaxFailed
            });
        }
        function ShowHTML(data) { alert(data); }
        function AjaxFailed(result) {
            alert('Failed to load');
        }

Now if you run this code. It’ll display the html content of the page. I ran it and it displayed as expected

GetAjaxHTML

Let’s also see the HTTP Headers that I have taken via firebug

HTTP Headers

GetRequest1

Also let’s see the response of the URL

Response

If you see the encircled area in both the above picture they are pointing to localhost.

If you see the URL in both AJAX call they are pointing to same domain. But have you ever tried to initiate an jQuery AJAX call to some other domain .

What I have done here, I am running my application from IIS and I added a domain for Testing (localtest.me) in IIS. So I changed the URL in my AJAX call as

OtherDomainNewBut now if you try to run this code, it would not run. Because now the URL targeting to other domain. Let’s see again the HTTP Headers and response.

GetRequestOther

Let’s see the Response

GetResponseOtherDomainNow if you see here in the above picture the encircled area, both are different and pointing to different domain and didn’t get any result.

But why?

As I already described that every AJAX request is built on XMLHTTPRequest object and XMLHTTPRequest has some security limitation. It follows same-origin policy, it means that any HTTP request using XMLHTTPRequest initiated by a web application, can be processed only if it loaded from same domain/origin. If it requests to any other domain it will not be successful.

But as now we make lots AJAX call and some times to third party web services, it becomes hurdle to our development. To overcome this issue W3C has come up with feature called Cross-Origin Resource Sharing (CORS) which enables cross site data transfer without compromising security. To use this , we require to add few new HTTP headers that allows to add set of other origins/domains and the content type that is required to transfer.

Also let’s understand what is meant by other domain/origin?

If I have a domains like mydomain.com and mydoman1.com so as it is clear from seeing that these are different domain. Similarly subdomains like abc.mydomain.com and xyz.mydomain.com are also considered as from different origin/domain. Also at certain times the url also contains port number so if the port number is different, it also be treated as from different origin.

So as a thumb rule, you can say if the portion of URL before first single slash is different, it would be considered as from different origin and same origin policy would not be applied.

So now, let’s again back to our example. To run our example, we need to add these custom headers.  ASP.NET provides a way to add these new headers by adding some config entry. so I added the following in my web.config

GetConfig

Now if we run the code it runs successfully. Let’s analyse again the HTTP Headers and Response.

GetrequestOtherSuccess

And the Response

GetresponseOtherSuccess

Now if you see the dark encircled area, they are pointing to different domain and yet got the response. But the successful result caused by the thin encircled area in header pic, which is a new header got added. And we made this entry in web.config

But what would happen if I change the URL that I used in my first sample as

 function GetRatingValues() {
            $.ajax({
                type: "Post",
                url: "http://localtest.me/TestCORS/First.aspx/GetRatingValues",
                contentType: "application/json; charset=utf-8",
                data: '',
                dataType: "json",
                success: AjaxSucceeded,
                error: AjaxFailed
            });
        }

And if you run it again, It would not run. because in my last example, I was using Get Request. For Post (type: “Post”)request I can  transfer some data back and forth to server. So here I need to define one more entry in web.config that will add another header in the request as

Postheader ConfigNow after adding it, if you run the code then it’ll run like a charm.

One more point, I’ll make a here that providing * for Access-Control-Allow-Origin is not a good Idea, because it allows to access any other domain URL so it’s if you specify the particular domains here.

Hope you all have enjoyed this post. Do share your feedback.

Thanks,
Brij

Error While Serailize/De-Serailize DateTime in JSON format : A Solution

Sometimes back, I was working on one my modules in my application. Here I had an of a Class which has some properties of DateTime type. Actually I was serializing the object using JavaScriptSerializer to serialize it in JSON format but later could not be able to deserialize it again.

So I thought of digging deep to this problem. So  I will be discussing it with an example. Let’s have a class Continue reading…

Call HTTPhandler from jQuery, Pass data and retrieve in JSON format

Download sample for here

Last few days ago, I was woking with HTTP handler. Here I was required to call handler from Client script. Later I found, that I need to pass some data to handler and also recieve some from it.

So I was looking for if there is some way we can pass some data to handler in some format and can recieve.

So Here I am going to share, How we can call a HTTPHandler from jQuery and can pass some data to handler and receive as well.

So Let’s go step by step Continue reading…

Javascript Dictionary

Might be some of you already know about Dictionaries in JavaScript. But recently I, worked on JavaScript dictionary. And that was really interesting and helpful for me. So I wanted to share my findings to you all. Please share your feedback for my posting.

JavaScript provides us a way to make a Dictionary object and use it as a C# dictionary. Although we would not be having all the properties that is supported by C# dictionary, but we will be able to use it as a normal dictionary i.e. in key value format.

Let’s see one simple example:

I have stored list of all week days as keys and assigned some numbers to these as values. Let’s see the code.

function CreateDayDictionary() {
var days = new Array();
days['Sunday'] = 1;
days['Monday'] = 2;
days['Tuesday'] = 3;
days['Wednesday'] = 4;
days['Thursday'] = 5;
days['Friday'] = 6;
days['Saterday'] = 7;
}

Now to fetch the values at any point of time, we can fetch as per the code given below. Here I have made a function to alert some data. It can be as

 function ShowDays() {
        alert(days['Sunday']);
        alert(days['Thursday']);
        alert(days['Saterday']);
    }

It will show three alerts, first 1 then 5 and lastly 7.

So we can store some global data in our page. And this data we can access, at different events, we require.

Similarly we can store objects in the dictionary in same way. Let’s see the code

 function CreateDictionarywithObject() {
        var objDictionary = new Array();
        // Creating a dictionary which is holding five objects
        for (var i = 0; i < 5; i++) {

            var obj= new myClass();
            obj.member1 = 'member1data' + i;
            obj.member2 = 'member2data' + i;
            obj.member3 = 'member3data' + i;

            objDictionary['Obj' + i] = obj;
        }
        //Fetching third Object
        var fetchedObj = objDictionary['Obj3'];
        alert(fetchedObj.member1);
        alert(fetchedObj.member2);
        alert(fetchedObj.member3);

    }

Now, one more thing if you want to pass the data from server to client as a JSON data, you can serialize a C# dictionary at server side, and again when you will desterilize at client side you will be getting the dictionary as we discussed above. Let’s see the magic.

Here I have made one class Employee as

public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public decimal Salary { get; set; }
    public int Age { get; set; }
}

Now, on the page load, I created a dictionary with some data, like below

List<Employee> employees= new List<Employee>()
        {
            new Employee{ Id=1000, Name="Brij", Age=27, Salary=800000},
            new Employee {Id=1001, Name = "Rahul", Age=28,Salary=500000},
            new Employee {Id=1002, Name = "Anoop", Age= 29 ,Salary = 60000}
        };
Dictionary<string, Employee> employeeData = employees.ToDictionary(em => em.Id.ToString(), emp => emp);

Now serialize the data using JavaScriptSerializer and assigned it in a hidden variable

JavaScriptSerializer ser = new JavaScriptSerializer();

hfData.Value = ser.Serialize(employeeData);

Now I have a textbox and a button to show employee details. My aspx code looks like this

<body>
    <form id="form1" runat="server">
    <div>
        <span>Id: </span> &nbsp;<input id="idName" type="text" /><br  />
        <input id="Button2" type="button" value="Displaydetail" onclick="show();"/>
        <asp:HiddenField ID="hfData" runat="server" />
    </div>
    </form>
</body>

Here I will be entering the Id of the employee, and on clicking the button “Show details”, I am displaying the data as JavaScript alerts. So let’s see the JavaScript code

function parseEmployeeData() {
        //for parsing the data
        employees = JSON.parse(document.getElementById("<%= hfData.ClientID%>").value);

    }

    function show() {
        parseEmployeeData();
        var key = document.getElementById('idName').value;
        var emp = employees[key];
        if (typeof (emp) != 'undefined') {
        // If key is found then dispaly the details
            alert(emp.Name);
            alert(emp.Age);
            alert(emp.Salary);
        }
        else {
        // key not found
            alert('No data found');
        }
    }

As you can see, first I am parsing the data using JSON, and then finding the value in the dictionary using some key and displaying the details as a JavaScript alert.
This sample is just for an example, to show how we can use JavaScript dictionary in our daily life.

Here, I have used namespace System.Web.Script.Serialization for serializing the data at C#. Also, I have included JSON JavaScript file in my application to parse the data at Client Side.

Happy Client Scripting

Thanks,

Brij