a developer's notes – a semi-technical web development BLOG

September 2, 2011

A Sample AJAX Script

Filed under: Javascript / JQuery — Duy Nguyen @ 2:51 am
Tags: , , , ,

Here is a sample AJax application. This was taken from “Ajax for Dummies”.

Here a user clicks on the “Display Message” button and it retrieves text from a text file and changes the text on the web page.

The application:


Here is the code:

<script language = “javascript”>

//Create the XMLHttpRequest object
var XMLHttpRequestObject = false;
 
if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
}
else if (window.ActiveXObject) { //For Internet Explorer only
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
}
 
//a function that takes a path for the datasource location and the div's ID to put the retrieved data into
function getData(dataSource, divID){
    if(XMLHttpRequestObject) {

        //find the div to put the data into
        var obj = document.getElementById(divID);

        //open(“method”, “URL”[, asyncFlag[, “userName”[, “password”]]])
        XMLHttpRequestObject.open(“GET”, dataSource); 

        //Set up the anonymous function to call when ready. The actual request isn't until later
        XMLHttpRequestObject.onreadystatechange = function() 
        {   
            //readState[ 0:uninitialize, 1:loading, 2:loaded, 3:interactive, 4:complete ]
            //status 200 = OK
            if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
                //data retrieved sucessfully so put the retrieved data into the div
                obj.innerHTML = XMLHttpRequestObject.responseText;
            }
        }
       
        //request server for data. And the anonymous function will handle the response back from the server
        XMLHttpRequestObject.send(null); //null is only used for GETs
    }
}

</script>
 
<body>
 
<H1>Fetching data with Ajax</H1>
    <form>
        <input type = 'button' value = 'Display Message' onclick = 'getData(‘http://localhost/ch01/data.txt’,‘targetDiv’)'>
    </form>
 
    <div id='targetDiv'>
        <p>The fetched data will go here.</p>
    </div>
 
</body>

The text file data.txt, contains:

This text was fetched using Ajax.

I hope this was simple enough. The interesting thing about this is that the function to handle the response is setup before the actual request call. Enjoy!

Advertisements

Skipping Assembly Strong Name Validation

You can disable strong name valildation on an assembly using the Strong Name tool that comes with Visual Studio.

Open the Visual Studio Command Prompt. This should be available on Start, All Program Files, Visual Studio 200x, Visual Studio Tools.

At the command prompt:
SN -Vr “c:\location of the assembly\myassembly.dll”

To re-enable verification:

SN -Vu “c:\location of the assembly\myassembly.dll”

Create a free website or blog at WordPress.com.