Click here to Skip to main content
Click here to Skip to main content

Ajax Tutorial for Beginners with XML & JSON: Part 2

, 3 Jan 2009 CPOL
Rate this:
Please Sign up or sign in to vote.
This article will give you a brief idea about Ajax with XML & JSON

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.

< 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.

XML JSON
< 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.

XML JSON
< 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.

{ "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.

{ "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.

  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.

    < 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>

  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.

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:

    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.

    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.

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

Let's have a look at our callback functions:

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.

    //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):

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 XML
Output with JSON

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)

Share

About the Author


Comments and Discussions

 
GeneralGood Article.. PinmemberMathiyarasan.B8-Jul-14 5:34 
GeneralMy vote of 5 PinmemberMd. Touhidul Alam Shuvo26-Jun-11 21:47 
GeneralGood artical Pinmemberlovejun20-Jun-10 7:19 
GeneralRe: Good artical Pinmemberbymgdotnet9-Aug-10 0:46 
GeneralVery basic tutorial on Ajax with JSON PinmemberBinodSuman30-May-09 6:12 
GeneralRe: Very basic tutorial on Ajax with JSON Pinmemberbymgdotnet9-Aug-10 0:45 
GeneralGood but very basic Pinmemberkashif.nisar29-Jan-09 7:22 
GeneralRe: Good but very basic Pinmemberbymgdotnet3-Feb-09 19:01 
QuestionIT is Very Good! But It Support FirxFox ?? PinmemberJLKEngine0083-Jan-09 17:37 
AnswerRe: IT is Very Good! But It Support FirxFox ?? Pinmemberbhupiyujuan13-Jan-09 1:59 
GeneralRe: IT is Very Good! But It Support FirxFox ?? PinmemberMd. Touhidul Alam Shuvo26-Jun-11 22:02 
GeneralConfused Pinmembertamash_ionut3-Jan-09 10:32 
GeneralResponse Status Range Pinmemberdpminusa3-Dec-08 9:46 
GeneralRe: Response Status Range Pinmemberbhupiyujuan3-Dec-08 19:23 
GeneralStill confused (confusion lasts from part 1) PinmemberGevorg27-Nov-08 5:38 
GeneralRe: Still confused (confusion lasts from part 1) Pinmemberbhupiyujuan28-Nov-08 5:15 
GeneralWCF, JQuery and JSONP Pinmemberedwin_vermeer27-Nov-08 0:55 
GeneralRe: WCF, JQuery and JSONP Pinmemberbhupiyujuan28-Nov-08 5:11 
GeneralXcelent Article PinmemberAbhijit Jana26-Nov-08 19:33 
GeneralRe: Xcelent Article Pinmemberbhupiyujuan26-Nov-08 20:18 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.1411023.1 | Last Updated 3 Jan 2009
Article Copyright 2008 by bhupiyujuan
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid