Click here to Skip to main content
15,867,686 members
Articles / Web Development / ASP.NET

Ajax Tutorial for Beginners with XML & JSON: Part 2

Rate me:
Please Sign up or sign in to vote.
4.83/5 (38 votes)
3 Jan 2009CPOL5 min read 184.1K   2.4K   121   20
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)



Comments and Discussions

 
GeneralGood Article.. Pin
Mathiyarasan.B8-Jul-14 4:34
Mathiyarasan.B8-Jul-14 4:34 
GeneralMy vote of 5 Pin
Md. Touhidul Alam Shuvo26-Jun-11 20:47
Md. Touhidul Alam Shuvo26-Jun-11 20:47 
really good for us...
GeneralGood artical Pin
lovejun20-Jun-10 6:19
lovejun20-Jun-10 6:19 
GeneralRe: Good artical Pin
bymgdotnet8-Aug-10 23:46
bymgdotnet8-Aug-10 23:46 
GeneralVery basic tutorial on Ajax with JSON Pin
BinodSuman30-May-09 5:12
BinodSuman30-May-09 5:12 
GeneralRe: Very basic tutorial on Ajax with JSON Pin
bymgdotnet8-Aug-10 23:45
bymgdotnet8-Aug-10 23:45 
GeneralGood but very basic Pin
kashif.nisar29-Jan-09 6:22
kashif.nisar29-Jan-09 6:22 
GeneralRe: Good but very basic Pin
bymgdotnet3-Feb-09 18:01
bymgdotnet3-Feb-09 18:01 
QuestionIT is Very Good! But It Support FirxFox ?? Pin
JLKEngine0083-Jan-09 16:37
JLKEngine0083-Jan-09 16:37 
AnswerRe: IT is Very Good! But It Support FirxFox ?? Pin
bhupiyujuan13-Jan-09 0:59
bhupiyujuan13-Jan-09 0:59 
GeneralRe: IT is Very Good! But It Support FirxFox ?? Pin
Md. Touhidul Alam Shuvo26-Jun-11 21:02
Md. Touhidul Alam Shuvo26-Jun-11 21:02 
GeneralConfused Pin
tamash_ionut3-Jan-09 9:32
tamash_ionut3-Jan-09 9:32 
GeneralResponse Status Range Pin
dpminusa3-Dec-08 8:46
dpminusa3-Dec-08 8:46 
GeneralRe: Response Status Range Pin
bhupiyujuan3-Dec-08 18:23
bhupiyujuan3-Dec-08 18:23 
GeneralStill confused (confusion lasts from part 1) Pin
Gevorg27-Nov-08 4:38
Gevorg27-Nov-08 4:38 
GeneralRe: Still confused (confusion lasts from part 1) Pin
bhupiyujuan28-Nov-08 4:15
bhupiyujuan28-Nov-08 4:15 
GeneralWCF, JQuery and JSONP Pin
edwin_vermeer26-Nov-08 23:55
edwin_vermeer26-Nov-08 23:55 
GeneralRe: WCF, JQuery and JSONP Pin
bhupiyujuan28-Nov-08 4:11
bhupiyujuan28-Nov-08 4:11 
GeneralXcelent Article Pin
Abhijit Jana26-Nov-08 18:33
professionalAbhijit Jana26-Nov-08 18:33 
GeneralRe: Xcelent Article Pin
bhupiyujuan26-Nov-08 19:18
bhupiyujuan26-Nov-08 19:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.