Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I refresh data dynamically without refreshing the entire page?

AJAX

How do I refresh data dynamically without refreshing the entire page?

by  djjd47130  Posted    (Edited  )
This can be done through using AJAX. AJAX isn't a programming language, but a technique and combination of different languages for a common practice. It can be considered the core basics behind server/client communication in a web page. AJAX stands for "Asynchronous JavaScript And XML", meaning it uses both JavaScript and XML.

Note: This code was written and assembled directly in this website, and is not tested. It's mostly copied from existing code and modified.

Original code was written in Microsoft Visual Studio 2010 Professional using ASP.NET with C#

First of all, most of the code will be generated through JavaScript. The page you will design will barely have any content in it. Start by creating an empty web page and replacing it with the code below.

ASPX File: Default.aspx
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DJJD.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" language="JavaScript" src="MyAJAX.js"></script>
    <script type="text/javascript" language="JavaScript">
        window.onload = function () {
            GetMyData();
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <div id="MyDiv">
            <br />
        </div>
    </div>
    </form>
</body>
</html>

There is a div on this page named MyDiv, which has <br /> in it only. The <br /> is only to make the div visible when there is no data, otherwise the div would not show at all. JavaScript is declared in the page's header assigning a method to the page's onload event. This function simply calls a function in the next file MyAJAX.js. The page also declares this file in the header as well.

JavaScript File: MyAJAX.js
Code:
var XmlHttp; //Object which retrieves data from server
var MyDataDBID = new Array(); //List of received Database ID's
var MyDataCaption = new Array(); //List of received Captions
function GetMyData() {
    //Identify type of browser and handle accordingly
    if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
    {
        XmlHttp = new XMLHttpRequest();
    }
    else // code for IE6, IE5
    {
        XmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //Assign response method    
    XmlHttp.onreadystatechange = ReceiveMyData;
    //Open and send request to server
    XmlHttp.open("GET", "/Command.aspx?CMD=GETDATA", true);
    XmlHttp.send();
}
function ReceiveMyData() {
    //Check if data is ready, if so, continue to reading the data
    if (XmlHttp.readyState == 4 && XmlHttp.status == 200) {        
        var xmlDoc = XmlHttp.responseXML; //Get xml data from response
        var x; //Temporary object to hold xml sub-data
        var NewCount = 0; //Temporary variable - how many new records are in XML
        //Don't read if nothing exists
        if (xmlDoc != null) {
            x = xmlDoc.getElementsByTagName("ID"); //Get list of all instances of the database id, or 'ID' from XML data
            NewCount = x.length; //Set new count to number of new records
            if (NewCount > 0) {
                //Loop through all instances of 'ID'
                for (i = 0; i < NewCount; i++) {
                    MyDataDBID[i] = x[i].childNodes[0].nodeValue; //Assign DBID array value
                }
                //Get list of all instances of 'Caption' from XML data
                x = xmlDoc.getElementsByTagName("Caption");
                //Loop through all instances of 'Caption'
                for (i = 0; i < NewCount; i++) {
                    NewCaption[i] = DecodeString(x[i].childNodes[0].nodeValue);
                }
                //Loop through all new records and create HTML for each
                var R = "<div style=\"width: 100%;\">"; //Temporary HTML code
                for (i = 0; i < NewCount; i++) {
                    R += "<div style=\"width: 100%; text-align: center; border: 1px solid;\">";
                    R += "DBID: " + MyDataDBID[i] + " | Caption: " + MyDataCaption[i];
                    R += "</div>";
                }
                R += "</div>";
                //Replace contents of 'MyDiv' with new HTML data
                document.getElementById("MyDiv").innerHTML = R;
            }
        }
    }    
}

Now we need to create the server page which receives the request from the user's page. This page is not visible, and is not intended to be browsed, but is simply there to receive the request from the client.

ASPX File: Command.aspx
Code:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Command.aspx.cs" Inherits="DJJD.Command" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

    </div>
    </form>
</body>
</html>

C# File: Command.aspx.cs
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Xml;

namespace DJJD
{
    public partial class Command : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string Cmd = Request.QueryString["CMD"].ToString();
            if (Cmd == "GETDATA")
            {
                using (MemoryStream S = new MemoryStream())
                {
                    XmlTextWriter XmlDoc = new XmlTextWriter(S, System.Text.Encoding.ASCII);
                    //Start the document
                    XmlDoc.WriteStartDocument();
                    XmlDoc.WriteStartElement("Items");

                    //You would put a loop here adding the XML data record by record

                        //Instead, I will create the records manually for this example

                        var X = 1;
                        XmlDoc.WriteStartElement("Item");
                        XmlDoc.WriteElementString("ID", X.ToString());
                        XmlDoc.WriteElementString("Caption", "This is the first record");
                        XmlDoc.WriteEndElement();

                        X = 2;
                        XmlDoc.WriteStartElement("Item");
                        XmlDoc.WriteElementString("ID", X.ToString());
                        XmlDoc.WriteElementString("Caption", "This is the second record");
                        XmlDoc.WriteEndElement();

                        X = 3;
                        XmlDoc.WriteStartElement("Item");
                        XmlDoc.WriteElementString("ID", X.ToString());
                        XmlDoc.WriteElementString("Caption", "This is the third record");
                        XmlDoc.WriteEndElement();

                    //End the document
                    XmlDoc.WriteEndElement();
                    XmlDoc.WriteEndDocument();
                    XmlDoc.Flush();
                    //Prepare the response
                    byte[] Data = S.ToArray();
                    Response.Clear();
                    Response.AppendHeader("Content-Disposition", "filename=MyAJAXTest.xml");
                    Response.AppendHeader("Content-Length", Data.Length.ToString());
                    Response.ContentType = "text/xml";
                    //Send the response
                    Response.BinaryWrite(Data);
                    XmlDoc.Close();
                }
            }
        }
    }
}

And that should be about it! When the page loads, it calls the function which sends the request. When the response is received, it will read the XML packet and display the data on the page.

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top