Naveen P.N

Just another Blog to play with programming

Archive for the ‘AJAX’ Category

Ready-State-Values

with one comment

Initially copy the XMLHttp-Initialize.js script file from the blog and run to know the ready state values of AJAX .And also create a txt file of name  async.txt and type  some text into it.

Ready-State-Values.html


<html>
<script type=”text/javascript” src=”XMLHttp-Initialize.js”></script>
<script type=”text/javascript”>
function process()
{
if(xhr)
{
try
{
xhr.open(“GET”, “async.txt”, true);
xhr.onreadystatechange = handleRequestStateChange;
xhr.send(null);
}
catch(e)
{
alert(“Can’t connect to server:\n” + e.toString());
}
}
}
function handleRequestStateChange()
{
myDiv = document.getElementById(“myDivElement”);
// display the status of the request
if (xhr.readyState == 1)
{
myDiv.innerHTML += “Request status: 1 (loading) <br/>”;
}
else if (xhr.readyState == 2)
{
myDiv.innerHTML += “Request status: 2 (loaded) <br/>”;
}
else if (xhr.readyState == 3)
{
myDiv.innerHTML += “Request status: 3 (interactive) <br/>”;
}
// when readyState is 4, we also read the server response
else if (xhr.readyState == 4)
{
// continue only if HTTP status is “OK”
if (xhr.status == 200)
{
try
{
// read the message from the server
response = xhr.responseText;
// display the message
myDiv.innerHTML += “Request status: 4 (complete). Server said: <br/>”;
myDiv.innerHTML += response;
}
catch(e)
{
alert(“Error reading the response: ” + e.toString());
}
}
else
{
// display status message
alert(“There was a problem retrieving the data:\n” + xmlHttp.statusText);
}
}
}
</script>
<body onload=’process()’>
Hello, server!

<br/>
<div id=”myDivElement” />
</body>
</html>



Download Code

Written by Naveen P.N

April 29, 2009 at 5:17 am

Initializing XMLHttpRequest Object

without comments

This is the standard way of initializing XMLHttpRequest Object

XMLHttp-Initialize.js

var xhr;
if(window.ActiveXObject)
{
try
{

xhr = new ActiveXObject(“Microsoft.XMLHTTP”);

}
catch (e)
{
xhr = false;
}

}
else
{
try
{
xhr = new XMLHttpRequest();
}

catch (e)
{
xhr = false;
}
}

Download Code

Written by Naveen P.N

April 29, 2009 at 5:08 am

Posted in AJAX

Sending Data using GET method

without comments

sendingdata-GET.html

<html>
<head>

<title>XMLHttpRequest - Sending Data with GET Query Strings </title>
<script type="text/javascript">
var xhr = false;
if (window.XMLHttpRequest)
{
	xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
	xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
function sendRequest(url)
{
	var value = document.getElementById("t1").value;
	var url = "http://localhost/Sending-Data-GET.php";
	var newurl=url+"?"+"t1="+value;
	if (xhr)
	{
		alert("xhr exists");
		xhr.open("GET",newurl,true);
		xhr.onreadystatechange = function()
		{
			if (xhr.readyState == 4 && xhr.status == 200)
			{
				var responseOutput = document.getElementById("responseOutput");
				responseOutput.innerHTML = xhr.responseText;
			}
		}
	}
xhr.send(null);
}
</script>
</head>
<body>
<h3>Send Data Using GET method Using Ajax</h3>
<form action="#" method="GET">

<input type="text" name="t1" id="t1">
<input type="button" name="rating" onclick="sendRequest();">
</form>
<br />
<div id="responseOutput">&nbsp;</div>
</body>
</html>

Sending-Data-GET.php


<?
$v=$_GET['t1'];
echo "Server Side Coding  $v";
?>

Written by Naveen P.N

March 24, 2009 at 5:39 am

Posted in AJAX

Tagged with ,

Display Time continiously

without comments

Time-Continous.html

  This sample code gets the time from server and display continiously using AJAX.

<html>
  <head>
    <title>AJAX with PHP: Quickstart</title>
    <script type="text/javascript">
// stores the reference to the XMLHttpRequest object
var xmlHttp=null;
if(window.ActiveXObject)
  {
    try
    {
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (e)
    {
      xmlHttp = false;
    }
  }
  // if running Mozilla or other browsers
  else
  {
    try
    {
      xmlHttp = new XMLHttpRequest();
    }
    catch (e)
    {
      xmlHttp = false;
    }
  }

// make asynchronous HTTP request using the XMLHttpRequest object
function process()
{

	if(xmlHttp)
	{
// proceed only if the xmlHttp object isn't busy
	if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0)
	{

    		xmlHttp.open("GET", "time.asp", true);
		xmlHttp.onreadystatechange = handleServerResponse;

  	}
  	else
        setTimeout('process()', 1000);
	}
	xmlHttp.send(null);
}

// executed automatically when a message is received from the server
function handleServerResponse()
{
  // move forward only if the transaction has completed
  if (xmlHttp.readyState == 4)
  {
    // status of 200 indicates the transaction completed successfully
    if (xmlHttp.status == 200)
    {
      // extract the XML retrieved from the server
      xmlResponse = xmlHttp.responseText;

      document.getElementById("divMessage").innerHTML =
                                            '<i>' + xmlResponse + '</i>';
      // restart sequence
      setTimeout('process()', 1000);
    }
    // a HTTP status different than 200 signals an error
    else
    {
      alert("There was a problem accessing the server: " + xmlHttp.statusText);
    }
  }
}

</script>
  </head>
  <body onload='process()'>
    Server Time:
    <div id="divMessage" />
  </body>
</html> 

Time.asp

<%
response.expires=-1
response.write(time)
%>

Written by Naveen P.N

March 24, 2009 at 5:29 am

Posted in AJAX

AJAX andXML

without comments

Hi before be telling about AJAX and XML Let be tell u what is XML .XML stands for Extensible Markup Language which is an International standards of data exchange .Briefly when a server sends any data to client it actually the XML data coming from server to client and the browser which acts as an interpreter interprets all the XML tags into human readable format which is XSLT.

 

AJAX-XML.html

 

<html>

<head>

<title>Using Ajax and XML</title>

<script language = “javascript”>

function getGuest()

{

var xhr;

if (window.ActiveXObject)

      {

            xhr = new ActiveXObject(“Microsoft.XMLHTTP”);

      }

      else if (window.XMLHttpRequest)

      {

            xhr = new XMLHttpRequest();

            xhr.overrideMimeType(“text/xml”);

      }

 

            xhr.onreadystatechange = function()

            {

                  if (xhr.readyState == 4 && xhr.status == 200)

                  {

                  var xmlDocument = xhr.responseXML;

                       

                        removeWhitespace(xmlDocument);

                       

                  displayGuest(xmlDocument);

                  }

            }

      xhr.open(“GET”, “students.xml”, true);

xhr.send(null);

}

function displayGuest (xmldoc)

{

var eventsNode, eventNode, peopleNode;

var firstNameNode, lastNameNode, displayText;

//This goes to inventory Node

eventsNode = xmldoc.documentElement;

eventNode = eventsNode.firstChild;<!–here the actuall code lies here the firstchild will refer to computer science –>

peopleNode = eventNode.firstChild;<!–Same as Above–>

personNode = peopleNode.firstChild;

alert(personNode.firstChild.nodeValue);

displayText = “The Luckypersonis ” + personNode.firstChild.nodeValue;

var target = document.getElementById(“targetDiv”);

target.innerHTML=displayText;

}

function removeWhitespace(xml)

{

var loopIndex;

for (loopIndex = 0; loopIndex < xml.childNodes.length;loopIndex++)

{

var currentNode = xml.childNodes[loopIndex];

if (currentNode.nodeType == 1) {

removeWhitespace(currentNode);

}

if (((/^\s+$/.test(currentNode.nodeValue))) &&

(currentNode.nodeType == 3)) {

xml.removeChild(xml.childNodes[loopIndex--]);

}

}

}

</script>

</head>

<body>

<h1>Using Ajax and XML</h1>

<form>

<input type = “button” value = “Get the tech guy”

onclick = “getGuest()”>

</form>

<div id=”targetDiv” width =100 height=100>

Who is  the Techi???????????

</div>

</body>

</html>

 Students.xml

<?xml version=”1.0″?>

<students>

      <computerscience>

            <section-A>

                  <student1>Naveen</student1>

                  <student2>Niraj</student>

            </section-A>

            <section-B>

                  <student1>Radhesh</student1>

                  <student2>Rakesh</student>

            </section-B>

      </computerscience>

        <electronics>

            <section-A>

                  <student1>Balraj</student1>

                  <student2>Parthu</student>

            </section-A>

      </electronics>

</students>

Written by Naveen P.N

September 17, 2008 at 11:51 am

The XMLHttpRequest class

without comments

Allows to interact with the servers, thanks to its methods and attributes which will be usefull in coding.

readyState       :the code successively changes value from 0 to 4 that means for “ready”.

status                :200 is OK 404  if the page is not found

responseText   :holds loaded data as a string of characters

responseXml    :holds an XML loaded file, DOM’s method allows to extract data.

onreadystatechange   :property that takes a function as value that is invoked when the readystatechange event is dispatched.

Written by Naveen P.N

September 16, 2008 at 12:20 pm

AJAX Enabled Page

without comments

The  power of AJAX is in the object called XMLHttp which has varius states which i exaplain in the upcoming articles. 

Let me give an example before demonstrating what exacly an AJAX iwith a demo Program on both Traditional script code and AJAX code.

Example Program

To display time using non AJAX JavaScript

TradionalWeb.html

 

 <html>

<body>

<script type=”text/javascript”>

function ajaxFunction()

  { 

window.open(“time.asp”);

}

</script>

<form name=”myForm”>

Name: <input type=”text” onkeyup=”ajaxFunction();” name=”username” />

Time: <input type=”text” name=”time” />

</form></body>

</html>

 The following code when it is ececuted each time it requires minimum of 2 seconds .Provided IIS(Internet Information Service) is installed and paste it in inetpub.

To run the program just type in RUN http:\\localhost\TradionalWeb.html

 

 

 

Written by Naveen P.N

September 16, 2008 at 12:09 pm

AJAX

without comments

In traditional JavaScript coding, if you want to get any information from a database or a file on the server, or send user information to a server, you will have to make an HTML form and GET or POST data to the server. The user will have to click the “Submit” button to send/get the information, wait for the server to respond, then a new page will load with the results.

Because the server returns a new page each time the user submits input, traditional web applications can run slowly and tend to be less user-friendly.

With AJAX, your JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object

With an HTTP request, a web page can make a request to, and get a response from a web server – without reloading the page. The user will stay on the same page, and he or she will not notice that scripts request pages, or send data to a server in the background.

To start, Ajax is just a buzzword that covers a set of technologies, including Dynamic HTML (DHTML) and the XMLHTTPRequest object. DHTML is a combination of three elements: Hypertext Markup Language (HTML), JavaScript code, and Cascading Style Sheets (CSS). Using JavaScript code on a Web page, you can change the page dynamically to add, remove, or change the content. That’s the dynamic portion of DHTML. JavaScript code uses the XMLHTTPRequest object to request data from the server after the page has been loaded.

 

Written by Naveen P.N

September 15, 2008 at 1:54 pm

Posted in AJAX

Tagged with ,

About AJAX

without comments

The term Ajax was actually coined by Jesse James Garret of Adaptive

Path.

Written by Naveen P.N

July 7, 2008 at 2:44 pm

Posted in AJAX