DCSIMG
Microsoft Ajax, from the bottom up - part 2. - Pini Dayan

Pini Dayan

The best thing about a boolean is even if you are wrong, you are only off by a bit.

Microsoft Ajax, from the bottom up - part 2.

In the previous post, i showed a simple ajax sample using the old traditional way.

Today we are going to improve our sample using JSON.

Before i'll explain what JSON is, lets do a little briefing about JavaScript. In javascript we can write object using this syntax:

<script> 
        var oEmployeeObj = new Object();
        oEmployeeObj.Name = "Yaniv";        
        oEmployeeObj.LastName = "Cohen";        
        oEmployeeObj.Age = "30"; 
        oEmployeeObj.Hobbies = new Array();
        oEmployeeObj.Hobbies[0] = "Playing soccer";      
        oEmployeeObj.Hobbies[1] = "C# 3.0"; 
        alert(oEmployeeObj.Hobbies[1]);
      </script>

As you can see , this is a simple object, representing an employee with some properties and one of them is an array of hobbies.This is by no means a way for creating a template object such in C# where we can instance it every time with a new values for our class member. Actually we can build templates of objects in JavaScript using the javascript prototyping (But this is beyond the scope of this post).

But as it turns out , you can write objects in a different syntax, This is exactly equivalent to the previous employee object.

 <script> 
       var oEmployeeObj = {    "Name":"Yaniv","LastName":"Cohen","Age":"30",
                                "Hobbies"  : ["Playing soccer","C# 3.0"]
                          }
                            
       
      alert(oEmployeeObj.Hobbies[1]);
 </script>
This is a subset of the language that allows this javascript syntax.
JSON 

JSON is Javascript object notation, which means it can be used as a data interchange
format. It is basically a way to define structures and it can use a a format for exchanging
data between Async calls when using ajax in an asp.net applications.
As we will see in later posts , it turns out that even asp.net ajax framework uses JSON as the default serializer.

This means that instead of telling our server to return an xml string when we use ajax to do it different:
1. We can return a JSON string.
2. We can still return an xml string but use parser (which can be downloaded from the web) to convert this xml into a  
   JSNO string.
3. We can even use javascript eval function to take this JSON string and convert it to an object. In this case
   We have a security issue since a malicious code can be injected to this string.

So lets see an example, which is an improvement for the previous one:

1. Here the aspx file code: (nothing new here)

<div dir=rtl>    
   <asp:DropDownList runat=server ID="ddlEmployees" onchange="CheckIfTeacher();">
       <asp:ListItem Text="pini" Value="pini"></asp:ListItem>
       <asp:ListItem Text="zohar" Value="zohar"></asp:ListItem>
       <asp:ListItem Text="eran" Value="eran"></asp:ListItem>    
   </asp:DropDownList>
       
   <br />
   <asp:Label runat=server ID="lblDetails" ></asp:Label><br />                            
   </div>

2.Here the js code:

var oXmlhttp;
       function CheckIfTeacher() 
       {
           //Get the selected name
           var ddlObj = document.getElementById("<%= ddlEmployees.ClientID %>");
           var indexSelected = ddlObj.selectedIndex;
           var sName = ddlObj.options[indexSelected].value;

           //Get details for the given user
           oXmlhttp = new ActiveXObject("Microsoft.XMLHTTP");                        
           var sURL = "http://localhost/AjaxTest/Ajax/GetTeacherDetails.aspx?sName=" + sName;
           oXmlhttp.open("GET", sURL, true);
           oXmlhttp.onreadystatechange = GotAnswer;
           oXmlhttp.send(null);           
       }

       function GotAnswer() 
       {
           // if xmlhttp shows "loaded"
           if (oXmlhttp.readyState == 4) 
           {              
               //if "OK"
               if (oXmlhttp.status == 200)
                {
                   var result = oXmlhttp.responseText;                    
                   
                   //Parse this xml                                        
                   var lblObj = document.getElementById("<%=lblDetails.ClientID %>");    
                   
                   var oJSONObject = xml2json.parser(result);                                                             
                   
                   //alert(oJSONObject);
                   //alert(xml2json.show_json_structure(oJSONObject));
                   
                   var sName = oJSONObject.userdata.name;                            
                   var sAge =  oJSONObject.userdata.age;              
                   var sHobbies = oJSONObject.userdata.hobbies;                   
                 
                   lblObj.innerHTML = "Name:"  + sName + " Age=" + sAge + " Hobbies:" + sHobbies;                    
               }
               else
                {
                   alert("Problem retrieving XML data");
                }
           }
       }    
   </script>

3. And here are the refrences to the JS files that uses the xml2json.parser(result) which converts an xml string into a JSON object:

<script language=javascript src="../Javascript/xml2json.js"></script>
The js file can be loaded from http://www.thomasfrank.se/xml_to_json.html
 
As you can see this the returning string now can be easily parsed using a javascript syntax instead of parsing an xml document which can be a pain in javascript.
 
 

Comments

David said:

Good article, there is a huge debate about xml vs JSON.

I think if you are familiar with them both its pretty much the same - that is if the limitations to JSON dont bother you.

# October 2, 2008 1:29 AM

Shlomo said:

יפה מאוד

# December 22, 2008 3:40 PM

Yaniv Cohen said:

Definitely JSON is more intuitive and easier then XML.

B.T.W: As i remember, the last time that i played soccer, i almost broke someone leg ;-)

# September 7, 2009 12:15 PM
Leave a Comment

(required) 

(required) 

(optional)

(required) 


Enter the numbers above: