Click here to Skip to main content
15,896,489 members
Articles / Web Development / ASP.NET
Article

ASP.NET, AJAX and XML: Creating a simple counter

Rate me:
Please Sign up or sign in to vote.
2.45/5 (5 votes)
21 Jul 2008CPOL2 min read 23.9K   176   14  
This article is a simple demonstration of how to use asp.net and Ajax to interact with an XML file

Introduction

Create a simple counter which increases every time a page loads. This uses Ajax and ASP.NET technology. Data is stored and retrieved in am XML file. Once the page is loaded it send a query via ajax to an ASP.NET file, this opens an xml file reads, writes, saves, and sends the result back. Meanwhile Ajax is waiting and listening for a response, once received it displayed and formats it.

More importantly this, simple project shows the power of ajax..and how simple it is to implement in your existing backend code. The

Using the Code

There are 3 parts for the code to work fine

1. CountViews.xml(XML):

XML
<?xml version="1.0" encoding="UTF-8"?><br><CountViews><br>  <views>1</views><br></CountViews>

This is your data source and will store and save the increment in the value of the counter. If you are not familiar with XML, google "XML tutorial".

2. CountViews.cs (C#):

C#
public partial class CountViews : System.Web.UI.Page
  {
  public string QQ = HttpContext.Current.Request.QueryString["QQ"];
  public string thePath = "CountViews.xml";<br>
  protected void Page_Load(object sender, EventArgs e)
  {
  count(Convert.ToInt32(QQ));
  }</p>
 public void count(int myQQ)
  {</p>
XmlDocument doc = new XmlDocument();<br>
  //LOAD XML FILE
  try
  {
  doc.Load(Server.MapPath(thePath));
  }<br>
  catch (Exception) { Response.Write("Couldn't load XML file. Check its permissions"); }</p>
//FIND THE REQUIRED NODE<br>
  string xPathID = "/CountViews/views";
  XmlElement myItem = (XmlElement)doc.SelectSingleNode(xPathID);<br>
  //GET CURRENT VALUE AND ADD INCREAMENT
  string views = (Convert.ToInt32(myItem.InnerText) + myQQ).ToString();
  myItem.InnerText = views;
  try
  {
  //SAVE INCREASED VALUE</p>
doc.Save(Server.MapPath(thePath));
  }
  catch (Exception) { Response.Write("Couldn't save value check the permissions of your xml file"); }</p>
 //OUTPUT NEW VALUE
  Response.Write(views);
  }</p>
}</p>

This is your typical cs backend code. A series of events happens when ajax delivers the query

1. The XML file is loaded into memory.
2. The current counter value is retrieved from the XML node
3. A simple calculations executes to get new counter value
4. The value is saved to the same XML file
5. The value is also returned which ajax receives.

3. DisplayViews.aspx (Ajax, Javascript, html):

JavaScript
<script type="text/javascript"></p>
function GetXmlHttpObject()
  {
  var xmlHttp=null;
  try
  {<br>
  // Firefox, Opera 8.0+, Safari<br>
  xmlHttp=new XMLHttpRequest();
  }
  catch (e)
  {
  // Internet Explorer
  try
  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch (e)
  {<br>
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
  }
  return xmlHttp;<br>
  }
  function ajaxUpdate(url, mydiv, QQ) {<br>
  xmlhttp=GetXmlHttpObject();
  if (xmlhttp==null)
  {
  alert ("Your browser does not support AJAX!");
  return;
  } <br>
  if (xmlhttp) {<br>
  xmlhttp.onreadystatechange = function() {<br>
  if ((xmlhttp.readyState == 4 || xmlhttp.readyState == 'complete') && xmlhttp.status == 200) {<br>
  document.getElementById(mydiv).innerHTML = xmlhttp.responseText;<br>
  }<br>
  } <br>
  xmlhttp.open("GET", url + "?q=" + Math.random()+ "&QQ="+QQ, true);<br>
  xmlhttp.send(null);<br>
  }<br>
  }</script></p>

<body onload="javascript:ajaxUpdate('CountViews.aspx','show_div','1');">
<form name="frmServerTime" id="frmServerTime"><br /><table border="0" cellpadding="4" cellspacing="0" id="Table2"> <br /><tr><td><br /><input type="button" name="btnTime" value=" +10 " id="btnTime" <br>onclick="javascript:ajaxUpdate('CountViews.aspx','show_div','10');" /><br><input type="button" name="btnTime" value=" +100 " id="Button1" <br>onclick="javascript:ajaxUpdate('CountViews.aspx','show_div','100');" /><br></td> <br /></tr> <br /><tr> <br /><td><div id="show_div" style="border:1px solid RED; width:100px; height:20px;"></div></td> <br /></tr> <br /></table></form><br /></body>

Ajax acts like a messenger. It will receive the query from the user rally it to the server then patiently wait for an answer. Once one is detected it displays it , to the user, preferably formatted with css.

The first function GetXmlHttpObject() creates a XMLHttpRequest based on what browser you are using. This is vital for ajax to work.

The next function ajaxUpdate(url, mydiv, QQ) is a method which passes 3 variables via ajax

1. url: The url where the file ajax is to be interacting is .
2. mydiv: The div area you want the result to be displayed
3. QQ: Any extra query you wish to send to your backend script via GET using ajax.

Also on this file (DisplayViews.aspx)is a simple html form which houses the user interface for the user. This has an onload event on the body tag which fires the function in javascript to increase the counter.

Points of Interest

I have also created 2 extra buttons which fires off the same function but with different values. One increases the counter by 10, the other by 100.
It shows how dynamic ajax can be. Did you also notice the speed..this is very obvious because the page doesn't load.

License

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


Written By
Technical Lead
United Kingdom United Kingdom
Ola Apata is a Technical IT Consultant who specialise is social media development, training and marketing. Ola resides in UK and has worked with big brand names

Comments and Discussions

 
-- There are no messages in this forum --