Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Ajax Tutorial for Beginners with XML & JSON: Part 2

4.83/5 (38 votes)
3 Jan 2009CPOL5 min read 187.6K   2.4K  
This article will give you a brief idea about Ajax with XML & JSON
Image 1

Introduction

In my first article "Ajax Tutorial for Beginners: Part 1" which you can read here, I discussed Ajax, how it works, and how to create an XMLHttpRequest object. Now let us play some more with Ajax. In this article, I will be explaining XML and JSON (JavaScript Object Notation). The purpose of explaining both XML and JSON technology is not to compare one to the other, but to distribute the knowledge of both, as I feel confident in saying many beginners are aware of XML but not JSON.

If you are hearing this word, "JSON," for the first time, please do not worry about it as it is more simple than XML and also simple to use in JavaScript.

I will not describe: What is JSON? How is it formed? When was it started? bla bla bla... All I will say to you guys is that it is a lightweight data-interchange format, which is easy to read and write. Now let's be more practical.

Learn to Convert any XML File into JSON

Let's quickly have a look into the following XML file.

XML
< weatherdetails>

	< weatherreport city="Mumbai" weather="32" ></weatherreport>
	< weatherreport city="Delhi" weather="28" ></weatherreport>

	< weatherreport city="Chennai" weather="34" ></weatherreport>
	< weatherreport city="Kolkata" weather="26" ></weatherreport>

< /weatherdetails>

This XML file gives weather details of the four major cities in India. Let's learn some basic things about how to convert this XML file into JSON.

XMLJSON
< xx>yyy< /xx>{ "xx":"yyy" }

See that above code < xx> is a tag which has the following value yyy. When converted to JSON this becomes { "xx" : "yyy" }. Let us take the above XML file and try to convert it now:

XML: < weatherdetails>yyy< /weatherdetails>

Note: I have replaced the inside part of < weatherdetails> to yyy for the time being.

JSON: From the conversion table, JSON will be:

{ "weatherdetails" : "yyy" },

Isn't it simple? Yes.

Ok, now what if we have attributes inside the tag? Let us take another scenario.

XMLJSON
< xx yy='nn'>< /xx>{ "xx": {"yy":"nn"} }

See the above code <xx> is a tag which has an attribute yy='nn', when we convert this into JSON it becomes { "xx" : {"yy":"nn"}}. Let's take the above XML file and try to convert now:

XML: < weatherreport city="Mumbai" weather="32" >< /weatherreport><br>
JSON: from the conversion table, JSON will be { "weatherreport" : {"city":"Mumbai",
   "weather":"32"} }

Now what if we have an array of the same tags. If this is the case, we have to use an array and place all the tags inside []. Like here in the XML file, there are four weatherreport tags, so we have to place all its attributes in an array. Let's see how.

XML
{ "weatherreport" :
	[
		{"city": "Mumbai", "weather": "32" },
		{"city": "Delhi", "weather": "28" },
		{"city": "Chennai", "weather": "34" },
		{"city": "Kolkata", "weather": "26" }
	]
}

Now in the first scenario, I have replaced all weatherreport tags to yyy, let's replace it with the above JSON code to get our final JSON output.

XML
{ "weatherdetails":
	{
		"weatherreport":
			[
			    {"city": "Mumbai", "weather": "32" },
			    {"city": "Delhi", "weather": "28" },
			    {"city": "Chennai", "weather": "34" },
			    {"city": "Kolkata", "weather": "26" }
			]
	}
}

Yes that's it, we have converted an XML file into JSON. Now let's use this XML and JSON file into Ajax together.

How Can we Use Ajax with XML Response and with JSON

In the code, I have explained that the response coming from the web server depends upon user selection, i.e. whether the user will select XML type or JSON. In this example, the user will type any one of the major cities in a textbox which will return the weather report of that city. You can add as many details as you want, right now I have only added weather temperature in degrees Celsius.

Ok let's start our weather report example in Ajax. See the below figure-1.

Image 2

  1. Web browser requests the content of just the part of the page that it needs to refresh.
  2. Web server analyzes the received request and builds up an XML message or JSON depend upon the user selection, which is then sent back to the web browser.
  3. After the web browser receives the XML/JSON message, it parses the message in order to update the content of that part of the page.

Ok, let's start building some front end for the user.

ASP.NET
< form id="form1" runat="server">

   < div>
    < h3>Small Ajax Application using XML & JSON to see the Weather
                  of a particular city < /h3>< br />
    < h5>( At present weather details is limited to four major cities
                  of India i.e. mumbai, delhi, chennai & kolkata )</h5>

    < br />
    Choose Type here :
    < asp:DropDownList runat="server" ID="ddlType" >
        < asp:ListItem Value="XML" Selected="True" >XML
            < /asp:ListItem>

        < asp:ListItem Value="JSON">JSON< /asp:ListItem>
    < /asp:DropDownList>
    < br />< br />

    Type the city here: < input type="text" id="txtCity"
                  onkeyup="FetchWeather(this.value)" />
    < br />

    < asp:Label runat="server" ID="lblWeather" />
< /div>
< /form>

Image 3

  1. User will select the type of the response he/she wants from the web server.
  2. User will type the city he/she wants to see the weather report.
  3. Here in our textbox we have fired an event 'onkeyup' which will call the FetchWeather() function.

Now let's have a look to our Ajax FetchWeather function which we have to write in the JavaScript part.

JavaScript
var xmlHttpRequest;
var type;
var _City;
function FetchWeather(city)
{
	_City = city.toLowerCase();

	xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() :
                     new ActiveXObject("Msxml2.XMLHTTP");

           	if (xmlHttpRequest == null)
		return;

	var ddlType = document.getElementById('ddlType');
	type = ddlType.options[ddlType.selectedIndex].text;

	xmlHttpRequest.open("GET",
                     "FetchWeather.aspx?city="+city+"&type="+type, true);
		if(type=='XML')
		xmlHttpRequest.onreadystatechange = StateChangeForXML;
	else if(type=='JSON')
		xmlHttpRequest.onreadystatechange = StateChangeForJSON;

           	xmlHttpRequest.send(null);
}
function StateChangeForXML()
{
	if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
	{
		document.getElementById(
                              '<%= lblWeather.ClientID %>').innerHTML =
                              xmlHttpRequest.responseText;
		document.getElementById('txtCity').focus();
	}
}
function StateChangeForJSON()
{
	if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
	{
		var json = eval('('+ xmlHttpRequest.responseText +')');
		for(var i=0; i < json.weatherdetails.weatherreport.length; i++)
		{
			if(
                              json.weatherdetails.weatherreport[i].city.toLowerCase() ==
                               _City)
			{
				document.getElementById(
                                         '< %= lblWeather.ClientID %>').innerHTML =
                                         '< br>Weather Report using JSON< br>

                                         '+json.weatherdetails.weatherreport[i].weather+
                                         '< sup>o< /sup> C <
                                         img src="/KB/ajax/AjaxTutorial2/weathericon.JPG"
                                         alt="weather" />';
				document.getElementById('txtCity').focus();
			}
		}
	}
}

I will explain the above code in small parts in a sequential manner.

  1. From the above code, we first create a XMLHttpRequest object:

    C#
    xmlHttpRequest = (window.XMLHttpRequest) ? new XMLHttpRequest() :
        new ActiveXObject("Msxml2.XMLHTTP");
  2. If the browser does not support Ajax, it will return false.

  3. Next we open our connection to the web server with our newly created XMLHttpRequest object. Here the FetchWeather.aspx page is the page from where we will get the XML/JSON response (pending on the user's selection). I am passing the city name and type in the form of querystring to the FetchWeather.aspx page.

    C#
    xmlHttpRequest.open("GET", "FetchWeather.aspx?city="+city+"&type="+type, true);
  4. Depending on the type, the XMLHttpRequest object will decide which function to be called onreadystatechange.

    C#
    if(type=='XML')
    	xmlHttpRequest.onreadystatechange = StateChangeForXML;
    else if(type=='JSON')
    	xmlHttpRequest.onreadystatechange = StateChangeForJSON;

Let's have a look at our callback functions:

C#
function StateChangeForXML()
{
	if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
	{
		document.getElementById('<%= lblWeather.ClientID %>').innerHTML =
                      xmlHttpRequest.responseText;
		document.getElementById('txtCity').focus();
	}
}
function StateChangeForJSON()
{
	if(xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
	{
		var json = eval('('+ xmlHttpRequest.responseText +')');
		for(var i=0; i < json.weatherdetails.weatherreport.length; i++)
		{
			if(
                               json.weatherdetails.weatherreport[i].city.toLowerCase() ==
                               _City)
			{
			document.getElementById(
                               '< %= lblWeather.ClientID %>').innerHTML =
                               '< br>Weather Report using JSON< br>

                               '+json.weatherdetails.weatherreport[i].weather+
                               '< sup>o< /sup> C <
                               img src="/KB/ajax/AjaxTutorial2/weathericon.JPG" alt="weather" />';
				document.getElementById('txtCity').focus();
			}
		}
	}
}
  1. xmlHttpRequest.status property retrieves the HTTP status code of the request. This property is a read-only property with no default value.

  2. Ok let's go in details for JSON function, i.e. StateChangeForJSON.

    Whatever text response coming from the Web Server is converted into an object with the help of the JSON eval procedure. Once we get the object, we can retrieve any data from it.

  3. As the request method we are sending is "GET" (remember it's case sensitive), there is no need to send any extra information to the server.

    C#
    //Send the Ajax request to the server with the GET data
    xmlHttpRequest.send(null);

In FetchWeather.aspx.cs the on Page_Load event writes the following code (which is our XML/JSON response message depending on type user selected):

C#
if ( type == "XML" )
{
	nodeList = doc.SelectNodes( "weatherdetails/weatherreport" );
	foreach ( XmlNode node in nodeList )
	{
		list2Ret.Add( new KeyValuePair<string, string>(
                      node.Attributes["city"].InnerText.ToLower(),
                      node.Attributes["weather"].InnerText ) );
	}
	for ( int i = 0; i < list2Ret.Count; i++ )
	{
		if ( list2Ret[i].Key == city.ToLower() )
			Response.Write("< br>Weather Report using XML < br>
                            "+ list2Ret[i].Value + "< sup>o< /sup> C"+ weatherIcon );
	}
}
else if ( type == "JSON" )
{
	string toJSON = byLibrary.byComponent.XmlToJSON( doc );
	Response.Write( toJSON );
}
  • In the XML type, we will send the weather of a given city which the user has typed in the TextBox. It's quite simple as I have explained in my first article which you can read from here.
  • I have used a byLibrary.dll in which there is a class named byComponent which has a method to convert XML to JSON directly which takes one parameter of XmlDocument.
Output with XMLImage 4
Output with JSONImage 5

History

  • 26th November, 2008: Initial post
  • 1st January, 2009: Article updated

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)