Results 1 to 4 of 4

Thread: Basic AJAJ

  1. #1

    Wink Basic AJAJ

    AJAJ: Asynchronos Javascript and JSON:

    Code to dynamically populate one checkbox (states) based on the choice in another (countries).

    To avoid having to pass all states for all countries in the HTML file, which would get pretty big, and produce a lot of traffic, we instead wait until the country has been selected, then we launch a XMLhttp request to the ashx handler, and load the states array posthumously, then populate the second combobox.

    The C# .ashx handler returns a JSON array of states for the selected country.
    The ashx handler runs on the server and gets his data from the database on the server.


    HTML
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html>
    <head>
    <title>Select Box AJAX Populate</title>
    
    <script type="text/javascript" language="javascript">
    function getHTTPObject() 
    {
    	if (window.XMLHttpRequest)  // code for IE7+, Mozilla, Chrome, Opera, Safari
    	{ 
    		var http = new XMLHttpRequest();
    		if (http.overrideMimeType) 
    		{
    			//http.overrideMimeType('text/text');
    			//http.overrideMimeType('text/html');
    			//http.overrideMimeType('text/xml');
    			//http.overrideMimeType('application/x-javascript');
    			//netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesRead");
    		}
    		return http;
    		
    	} 		
    	else if (window.ActiveXObject) // IE < 7
    	{ 
    		var AllHosteLittleParsers = ["Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
    		for (var parserID in AllHosteLittleParsers) 
    		{
    			try
    			{
    				return new ActiveXObject(AllHosteLittleParsers[parserID]);
                }
    			catch(e)
    			{ /* Not this parser */ }
    		}
    		alert("Awwww snap, you're using those crappy old MS programs...");
    		return null;
    	}
    	
    	alert('Browser or Browser version not supported.\nFailed to create XMLHttpRequest');
    	return null;
    }
    
    
    function state_Change(xmlhttp)
    {
    		alert(xmlhttp.readyState);
    		alert(xmlhttp.status);
    		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    		{
    			document.getElementById('test').innerHTML=xmlhttp.responseText
    		}
    		else if (http.status == 401)
    		{
    			alert('Cannot access cross domain information.');
    		}
    		else if (http.status == 0 && xmlhttp.readyState != 0)
    		{
    			alert('Cannot access cross domain information.');
    		}
    }
    
    function RetrieveDropDownData(xmlhttp)
    {
    	// Retrieve Data, call populate
    	alert(xmlhttp.responseText);
    }
    
    
    function loadXMLDocAsynchronous(url)
    {
    	var xmlhttp = getHTTPObject();
    	if (xmlhttp == null || xmlhttp == 'undefined')
    	{
    		alert("Cancel http request.");
    		return;
    	}
    	
    	
    	
    	xmlhttp.onreadystatechange=function()
    	{
    		//alert(xmlhttp.readyState);
    		//alert(xmlhttp.status);
    		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    		{
    			RetrieveDropDownData(xmlhttp);
    			//document.getElementById('test').innerHTML=xmlhttp.responseText
    		}
    		else if (xmlhttp.status == 401)
    		{
    			alert('Access denied.');
    		}
    		else if (xmlhttp.status == 0)
    		{
    			alert('Cannot access cross domain information.');
    		}
    	}
    
    	xmlhttp.open("GET",url,true);
    	if(xmlhttp.timeout)
    	{
    		xmlhttp.timeout = 15000;
    		xmlhttp.ontimeout = timeoutFired;
    	}
    	xmlhttp.setRequestHeader("Cache-Control", "no-cache");
    	xmlhttp.send(null);
    }
    
    
    function loadJSONSynchronous(url)
    {
    	var xmlhttp = getHTTPObject();
    	if(xmlhttp == null || xmlhttp == 'undefined')
    	{
    		alert("HTTP AJAX request cancelled, because you have one of those crappy browsers that do not support AJAX...");
    		return;
    	}
    
    	xmlhttp.open("GET",url,false);
    	if(xmlhttp.timeout)
    	{
    		xmlhttp.timeout = 15000;
    		xmlhttp.ontimeout = timeoutFired;
    	}
    	xmlhttp.setRequestHeader("Cache-Control", "no-cache");
    	xmlhttp.send(null);
    	
    
    	//alert(xmlhttp.readyState);
    	//alert(xmlhttp.status);
    	//state_Change(xmlhttp);
    	
    	return xmlhttp.responseText;
    	//document.getElementById('test').innerHTML=xmlhttp.responseText;
    }
    
    
    function PopulateDropDown(CallingDropdown)
    {
    	//alert(CallingDropdown.options[CallingDropdown.selectedIndex].value);
    	//alert(document.getElementById('Countries').innerHTML);
    	var DropDown2Populate = document.getElementById('States');
    	DropDown2Populate.disabled=false;
    	myOnChange = new Function("e", "location.href=this.options[this.selectedIndex].value");
    	DropDown2Populate.onchange = myOnChange;
    	
    	var txtResponse = loadJSONSynchronous('http://localhost/jsontest/CountryStatesGrabber.ashx?SelectedCountry='+escape(CallingDropdown.options[CallingDropdown.selectedIndex].text));
    	var astrStates=new Array(); // condensed array
    	astrStates=eval(txtResponse);
    	/*
    	switch (CallingDropdown.options[CallingDropdown.selectedIndex].text)
    	{
    		case "Afghanistan":
    			astrStates=["Badakhshan", "Badghis", "Baghlan", "Balkh", "Bamian", "Farah", "Faryab", "Ghazni", "Ghowr", "Helmand", "Herat", "Jowzjan", "Kabul", "Kandahar", "Kapisa", "Konarha", "Kondoz", "Laghman", "Lowgar", "Nangarhar", "Nimruz", "Paktia", "Paktika", "Parwan", "Samangan", "Sar-e Pol", "Takhar", "Uruzgan", "Wardak", "Zabul"]; // literal array
    			break;
    		case "Albania":
    			astrStates=["Berat", "Bulqize", "Delvine", "Devoll", "Diber", "Durres", "Elbasan", "Fier", "Gjirokaster", "Gramsh", "Has", "Kavaje", "Kolonje", "Korce", "Kruje", "Kucove", "Kukes", "Lac", "Lezhe", "Librazhd", "Lushnje", "Malesia e Madhe", "Mallakaster", "Mat", "Mirdite", "Peqin", "Permet", "Pogradec", "Puke", "Sarande", "Shkoder", "Skrapar", "Tepelene", "Tirane", "Tropoje", "Vlore"];
    			break;
    			
    		case "Aruba":
    			astrStates=["Brasil", "Bubali", "Ceru Colorado", "Cura Cabai", "Madiki", "Malmok", "Noord", "Oranjestad", "Piedra Plat", "Ponton", "Pos Chikitu", "San Nicolas", "Santa Cruz", "Savaneta", "Wayaca"];
    			break;
    			
    		case "America":
    			astrStates=["California", "Texas", "New York", "Florida", "Illinois", "Pennsylvania", "Ohio", "Michigan", "Georgia", "North Carolina", "New Jersey", "Virginia", "Washington", "Arizona", "Massachusetts", "Indiana", "Tennessee", "Missouri", "Maryland", "Wisconsin", "Minnesota", "Colorado", "Alabama", "South Carolina", "Louisiana", "Kentucky", "Puerto Rico", "Oregon", "Oklahoma", "Connecticut", "Iowa", "Mississippi", "Arkansas", "Kansas", "Utah", "Nevada", "New Mexico", "West Virginia", "Nebraska", "Idaho", "Maine", "New Hampshire", "Hawaii", "Rhode Island", "Montana", "Delaware", "South Dakota", "Alaska", "North Dakota", "Vermont", "District of Columbia", "Wyoming", "Guam", "U.S. Virgin Islands", "Northern Mariana Is.", "American Samoa"];
    			break;
    		default:
    			astrStates=["No match in the database"];
    	}
    	*/
    	
    	astrStates.sort(); // Forgot to sort US States
    	//http://www.javascriptkit.com/javatutors/arraysort.shtml
    	//astrStates.reverse(); // Descending order
    	
    	DropDown2Populate.innerHTML="";
    	// DropDown2Populate.innerHTML='<option value="" selected="true">--- Please Select ---</option>';
    	var theOption=document.createElement("OPTION");
    	var theText=document.createTextNode("--- Please Select ---");
    	theOption.appendChild(theText);
    	// theOption.setAttribute("value","Tutorial.htm");
    	// theOption.setAttribute("text","Tutorial.htm");
    	// theOption.text="Alabama";
    	DropDown2Populate.appendChild(theOption);
    	
    	
    	for(var i=0; i<astrStates.length;++i)
    	{
    		theOption=document.createElement("OPTION");
    		theText=document.createTextNode(astrStates[i]);
    		theOption.appendChild(theText);
    		theOption.value="http://www.wolframalpha.com/input/?i="+ astrStates[i];
    		DropDown2Populate.appendChild(theOption);
    	}	
    }
    
    
    
    </script>
    <head>
    
    <body>
    
    
    <select id="Countries" onchange="PopulateDropDown(this)">
      <option value="volvo">Afghanistan</option>
      <option value="saab">Albania</option>
      <option value="mercedes">Aruba</option>
      <option value="audi">America</option>
      <option value="volvo" selected="true">--- Please select ---</option>
    </select>
    <br />
    <br />
    <br />
    <!-- multiple="multiple" size="2" -->
    <select id="States" disabled="true" >
    	<option value="Testentry.htm" >Test entry</option>
    	<option selected="true" value="">--- Please Select ---</option>
    </select>
    
    <button type="button" onclick="javascript:PopulateDropDown();">Populate Dropdown</button>
    
    </body>
    </html>

    Serverside code:
    Code:
    using System;
    using System.Collections.Generic;
    using System.Web;
    
    namespace JSONserializer
    {
        /// <summary>
        /// Summary description for CountryStatesGrabber
        /// </summary>
        public class CountryStatesGrabber : IHttpHandler
        {
    
            public void ProcessRequest(HttpContext context)
            {
                context.Response.ContentType = "text/plain";
                string[] astrAllStates ;
    
                string strCountry = context.Request.QueryString["SelectedCountry"];
                
    	
    	
    	switch (strCountry)
    	{
    		case "Afghanistan":
    			astrAllStates=new string[]{"Badakhshan", "Badghis", "Baghlan", "Balkh", "Bamian", "Farah", "Faryab", "Ghazni", "Ghowr", "Helmand", "Herat", "Jowzjan", "Kabul", "Kandahar", "Kapisa", "Konarha", "Kondoz", "Laghman", "Lowgar", "Nangarhar", "Nimruz", "Paktia", "Paktika", "Parwan", "Samangan", "Sar-e Pol", "Takhar", "Uruzgan", "Wardak", "Zabul"}; // literal array
    			break;
    		case "Albania":
    			astrAllStates=new string[]{"Berat", "Bulqize", "Delvine", "Devoll", "Diber", "Durres", "Elbasan", "Fier", "Gjirokaster", "Gramsh", "Has", "Kavaje", "Kolonje", "Korce", "Kruje", "Kucove", "Kukes", "Lac", "Lezhe", "Librazhd", "Lushnje", "Malesia e Madhe", "Mallakaster", "Mat", "Mirdite", "Peqin", "Permet", "Pogradec", "Puke", "Sarande", "Shkoder", "Skrapar", "Tepelene", "Tirane", "Tropoje", "Vlore"};
    			break;
    			
    		case "Aruba":
    			astrAllStates=new string[]{"Brasil", "Bubali", "Ceru Colorado", "Cura Cabai", "Madiki", "Malmok", "Noord", "Oranjestad", "Piedra Plat", "Ponton", "Pos Chikitu", "San Nicolas", "Santa Cruz", "Savaneta", "Wayaca"};
    			break;
    			
    		case "America":
    			astrAllStates=new string[]{"California", "Texas", "New York", "Florida", "Illinois", "Pennsylvania", "Ohio", "Michigan", "Georgia", "North Carolina", "New Jersey", "Virginia", "Washington", "Arizona", "Massachusetts", "Indiana", "Tennessee", "Missouri", "Maryland", "Wisconsin", "Minnesota", "Colorado", "Alabama", "South Carolina", "Louisiana", "Kentucky", "Puerto Rico", "Oregon", "Oklahoma", "Connecticut", "Iowa", "Mississippi", "Arkansas", "Kansas", "Utah", "Nevada", "New Mexico", "West Virginia", "Nebraska", "Idaho", "Maine", "New Hampshire", "Hawaii", "Rhode Island", "Montana", "Delaware", "South Dakota", "Alaska", "North Dakota", "Vermont", "District of Columbia", "Wyoming", "Guam", "U.S. Virgin Islands", "Northern Mariana Is.", "American Samoa"};
    			break;
            default:
                astrAllStates = new string[] { "No match in the database" };
                break;
    	}
    
    
    
                
                // In System.Web.Extensions
                System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
                context.Response.Write(serializer.Serialize(astrAllStates));
            }
    
    
            public bool IsReusable
            {
                get
                {
                    return false;
                }
            }
        }
    }
    -----------------------------------------------------------------------



    And an example with Cross-Site scripting: Getting google suggestions for a search term:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html>
    <head>
    <title>Google Suggest AJAX</title>
    
    <script type="text/javascript" language="javascript">
    
    function GoogleSuggest(JSONresponse)
    {
    	if(JSONresponse[1])
    	{
    		var strSuggestList ="Suggestions for keyword: " + JSONresponse[0] +"\n------------------------\n";
    		for(var i=0; i<JSONresponse[1].length;++i)
    		{
    			strSuggestList+=JSONresponse[1][i][0]+ " (" + JSONresponse[1][i][1]+")\n";
    			//alert(JSONresponse[1][i][2]);
    		}
    		alert(strSuggestList);
    	}
    }
    
    
    function GetSearchSuggestion()
    {	
    	var s = document.createElement('script');
    	s.src = 'http://google.com/complete/search?q=' + document.getElementById('txtSearchText').value + '&callback=GoogleSuggest' ;
    	//s.onload = somecallbackfunction;
    	s.type = 'text/javascript';
    
    
    	//http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en|it&callback=foo
    	//http://ajax.googleapis.com/ajax/services/language/detect?v=1.0&q=hello&callback=foo
    	//http://google.com/complete/search?q=lol
    
    
    	if(document.getElementsByTagName('head').length > 0)
    		document.getElementsByTagName('head')[0].appendChild(s);
    }
    
    </script>
    
    <body>
    <input id="txtSearchText" type="text" value="Test" />
    <button type="button" onclick="javascript:GetSearchSuggestion();">Request JSON Callback</button>
    
    <!--
    ASP.NET: Server.ScriptTimeout = 180 
             Session.Timeout = 45
    http://code.google.com/apis/ajaxsearch/documentation/reference.html
    
    http://ajax.googleapis.com/ajax/services/search/blogs?v=1.0&q=Paris%20Hilton
    http://ajax.googleapis.com/ajax/services/search/news?v=1.0&q=Paris%20Hilton
    http://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=Paris%20Hilton
    http://ajax.googleapis.com/ajax/services/search/video?v=1.0&q=Paris%20Hilton
    http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton
    http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=hello%20world&langpair=en%7Cde
    -->
    
    </body>
    </html>


    Another example - you have to replace the api key, this one is wrong
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html>
    <head>
    <title>Get Synonyms - JSON</title>
    
    <script type="text/javascript" language="javascript">
    
    	function OnReceiveSynonym(JSONresponse)
    	{
    		/*
    		var myObject = eval('(' + myJSONtext + ')');
    		The eval function is very fast. 
    		However, it can compile and execute any JavaScript program, so there can be security issues. 
    		The use of eval is indicated when the source is trusted and competent. 
    		It is much safer to use a JSON parser
    		*/
    		
    		if(JSONresponse.noun)
    		{
    			if(JSONresponse.noun.ant)
    			{
    				for(var i=0;i<JSONresponse.noun.ant.length;++i)
    					alert(JSONresponse.noun.ant[i]);
    			}
    		}
    		
    		
    		if(JSONresponse.noun)
    		{
    			if(JSONresponse.noun.rel)
    				for(var i=0;i<JSONresponse.noun.rel.length;++i)
    					alert(JSONresponse.noun.rel[i]);
    		}
    		
    		
    		if(JSONresponse.noun)
    		{
    			if(JSONresponse.noun.sim)
    				for(var i=0;i<JSONresponse.noun.sim.length;++i)
    					alert(JSONresponse.noun.sim[i]);
    		}
    		
    		if(JSONresponse.noun)
    		{
    			if(JSONresponse.noun.syn)
    				for(var i=0;i<JSONresponse.noun.syn.length;++i)
    					alert(JSONresponse.noun.syn[i]);
    		}
    		
    		
    		/*
    		alert(JSONresponse.verb.syn[1]);
    		JSONresponse.verb.ant
    		JSONresponse.verb.rel
    		JSONresponse.verb.sim
    		JSONresponse.verb.syn
    		
    		JSONresponse.adjective.ant
    		JSONresponse.adjective.rel
    		JSONresponse.adjective.sim
    		JSONresponse.adjective.syn
    		
    		
    		JSONresponse.adverb.ant
    		JSONresponse.adverb.rel
    		JSONresponse.adverb.sim
    		JSONresponse.adverb.syn
    		*/
    		
    	}
    
    /*
    OnReceiveSynonym({"noun":{"syn":["passion","beloved","dear","dearest","honey","sexual love","erotic love","lovemaking","making love","love life","concupiscence","emotion","eros","loved one","lover","object","physical attraction","score","sex","sex activity","sexual activity","sexual desire","sexual practice"],
    "ant":["hate"],"usr":["amour"]},
    "verb":{"syn":["love","enjoy","roll in the hay","make out","make love","sleep with","get laid","have sex","know","do it","be intimate","have intercourse","have it away","have it off","screw","jazz","eff","hump","lie with","bed","have a go at it","bang","get it on","bonk","copulate","couple","like","mate","pair"],
    "ant":["hate"]}});
    OnReceiveSynonym({"adjective":{"syn":["first-class","fantabulous"],"sim":["superior"]}});
    */
    
    
    
    function GetSynonym()
    {
    	//window.appendChild(google);
    	
    	//window.google.ac.h(["aimbot",[["aimbot for combat arms","120,000 results","0"],["aimbots","274,000 results","1"],["aimbots.net","1,260,000 results","2"],["aimbot for cod4","251,000 results","3"],["aimbot download","1,570,000 results","4"],["aimbot for crossfire","116,000 results","5"],["aimbot for xbox 360","149,000 results","6"],["aimbot modern warfare 2","162,000 results","7"],["aimbot for combat arms free download","39,000 results","8"],["aimbot for halo","532,000 results","9"]]]);
    	
    	
    	var s = document.createElement('script');
    	
    	// http://words.bighugelabs.com/api/2/9d472299ce90f3304c63dc773025f36e/love/json?callback=OnReceiveSynonym
    	s.src = 'http://words.bighugelabs.com/api/2/9d472299ce90f3304c63dc773025f36e/' + document.getElementById('txtSynonym').value + '/json?callback=OnReceiveSynonym';
    	//s.onload = somecallbackfunction;
    	s.type = 'text/javascript';
    
    
    	if(document.getElementsByTagName('head').length > 0)
    		document.getElementsByTagName('head')[0].appendChild(s);
    }
    
    /*
    	var lol = {"noun":{"syn":["passion","beloved","dear","dearest","honey","sexual love","erotic love","lovemaking","making love","love life","concupiscence","emotion","eros","loved one","lover","object","physical attraction","score","sex","sex activity","sexual activity","sexual desire","sexual practice"]
    	,"ant":["hate"],"usr":["amour"]},
    	"verb":{"syn":["love","enjoy","roll in the hay","make out","make love","sleep with","get laid","have sex","know","do it","be intimate","have intercourse","have it away","have it off","screw","jazz","eff","hump","lie with","bed","have a go at it","bang","get it on","bonk","copulate","couple","like","mate","pair"]
    	,"ant":["hate"]}};
    	alert(lol.verb.syn[1]);
    */
    
    
    /*
    	var records = {
        "data" : [
            {
                "First Name" : "Bob",
                "Last Name" : "Smith",
                "Email" : "bsmith@someurl.com",
                "Phone" : "(555) 555-1212",
            },
            {
                "First Name" : "Jan",
                "Last Name" : "Smith",
                "Email" : "jsmith@someurl.com",
                "Phone" : "(555) 555-3434",
            },
            {
                "First Name" : "Sue",
                "Last Name" : "Smith",
                "Email" : "ssmith@someurl.com",
                "Phone" : "(555) 555-5656",
            }
        ]
    };
    	
    	//alert(records.data[0]["First Name"]);
    	//alert(records.data[0]["Last Name"]);
    	//alert(records.data[0].Email);
    	//alert(records.data[0].Phone);
    	
    
    */
    
    </script>
    </head>
    
    <body>
    <input id="txtSynonym" type="text" value="Test" />
    <button type="button" onclick="javascript:GetSynonym();">Request JSON Callback</button>
    </body>
    </html>


    And finally, we go from synchronous to asynchronous:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
    <html>
    <head>
    <title>AJAX GridView</title>
    
    <script type="text/javascript" language="javascript">
    
    function getHTTPObject() 
    {
    	if (window.XMLHttpRequest)  // code for IE7+, Mozilla, Chrome, Opera, Safari
    	{ 
    		var http = new XMLHttpRequest();
    		if (http.overrideMimeType) 
    		{
    			//http.overrideMimeType('text/text');
    			//http.overrideMimeType('text/html');
    			//http.overrideMimeType('text/xml');
    			//http.overrideMimeType('application/x-javascript');
    			//netscape.security.PrivilegeManager.enablePrivilege("UniversalPreferencesRead");
    		}
    		return http;
    		
    	} 		
    	else if (window.ActiveXObject) // IE < 7
    	{ 
    		var AllHosteLittleParsers = ["Msxml2.XMLHTTP.6.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
    		for (var parserID in AllHosteLittleParsers) 
    		{
    			try
    			{
    				return new ActiveXObject(AllHosteLittleParsers[parserID]);
                }
    			catch(e)
    			{ /* Not this parser */ }
    		}
    		alert("Awwww snap, you're using those crappy old MS programs...");
    		return null;
    	}
    	
    	alert('Browser or Browser version not supported.\nFailed to create XMLHttpRequest');
    	return null;
    }
    
    
        
    function state_Change(xmlhttp)
    {
    		alert(xmlhttp.readyState);
    		alert(xmlhttp.status);
    		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    		{
    			document.getElementById('test').innerHTML=xmlhttp.responseText
    		}
    		else if (http.status == 401)
    		{
    			alert('Cannot access cross domain information.');
    		}
    		else if (http.status == 0 && xmlhttp.readyState != 0)
    		{
    			alert('Cannot access cross domain information.');
    		}
    }
    
    function timeoutFired()
    {
    	alert("timeout!!!");
    }
    
    
    function loadXMLDocSynchronous(url)
    {
    	var xmlhttp = getHTTPObject();
    	if(xmlhttp == null || xmlhttp == 'undefined')
    	{
    		alert("HTTP AJAX request cancelled, because you have one of those crappy browsers that do not support AJAX...");
    		return;
    	}
    
    	xmlhttp.open("GET",url,false);
    	if(xmlhttp.timeout)
    	{
    		xmlhttp.timeout = 15000;
    		xmlhttp.ontimeout = timeoutFired;
    	}
    	xmlhttp.setRequestHeader("Cache-Control", "no-cache");
    	xmlhttp.send(null);
    	
    
    	//alert(xmlhttp.readyState);
    	//alert(xmlhttp.status);
    	//state_Change(xmlhttp);
    	
    	document.getElementById('test').innerHTML=xmlhttp.responseText;
    }
    
    
    
    function LoadXML(xmlhttp)
    {	
    	var x;
    	//alert(xmlhttp.responseXML.documentElement.tagName); // CATALOG
    	//alert(); // CD, for non IE
    	//alert(); // CD, for non IE
    	
    	var TableNames = new Array ();
    	
    	if(document.all)
    	{
    		var strCollectionElement=xmlhttp.responseXML.documentElement.childNodes[0].tagName;// CD
    		//x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
    		x=xmlhttp.responseXML.documentElement.getElementsByTagName(strCollectionElement);
    		for(var j=0; j < xmlhttp.responseXML.documentElement.childNodes[0].childNodes.length;++j)
    		{
    			TableNames[j]= xmlhttp.responseXML.documentElement.childNodes[1].childNodes[j].nodeName;
    		}
    	}
    	else
    	{
    		var strCollectionElement=xmlhttp.responseXML.documentElement.childNodes[1].tagName; //CD
    		x=xmlhttp.responseXML.documentElement.getElementsByTagName(strCollectionElement);
    		
    		for(var j=0; j < xmlhttp.responseXML.documentElement.childNodes[1].childNodes.length;++j)
    		{
    			if(xmlhttp.responseXML.documentElement.childNodes[1].childNodes[j].nodeType==3)
    				continue;
    			
    			TableNames[Math.floor(j/2)]= xmlhttp.responseXML.documentElement.childNodes[1].childNodes[j].nodeName;
    			//alert(xmlhttp.responseXML.documentElement.childNodes[1].childNodes[j].tagName); //TITLE
    		
    		}
    	}	
    	
    	var strTable="";
    	//strTable+="<table>";
    	var strHeader="<tr>";
    
    	for(var k=0; k < TableNames.length;++k)
    	{
    		strHeader+='<th style="width: 50mm; text-align: left;">'+TableNames[k]+'</th>';
    		//alert(TableNames[k]);
    	}
    	
    	strHeader+="</tr>";
    	
    	document.getElementById('mytableheader').innerHTML=strHeader;
    	//strTable+=strHeader;
    	
    	for (var l=0;l<x.length;l++)
    	{
    		strTable+='<tr>';
    		for(var m=0; m < TableNames.length;++m)
    		{
    			strTable+='<td>';
    			y=x[l].getElementsByTagName(TableNames[m]);
    			var strThisNode;
    			if(y[0].firstChild == null)
    				strThisNode = '';
    			else
    				strThisNode =y[0].firstChild.nodeValue;
    			//alert(strThisNode);
    			strTable+=strThisNode;
    			strTable+='</td>';
    		}
    		strTable+='</tr>';
    	}
    
    
    	//strTable+="</table>";
    	/*
    	<THEAD id="mytableheader">
    	<TFOOT id="mytablefooter">
    	<TBODY id="firstBlock">
    	<TBODY id="secondBlock">
    	*/
    	document.getElementById('secondBlock').innerHTML=strTable;
    }
    
    
    
    function loadXMLDocAsynchronous(url)
    {
    	var xmlhttp = getHTTPObject();
    	if (xmlhttp == null || xmlhttp == 'undefined')
    	{
    		alert("Cancel http request.");
    		return;
    	}
    	
    	
    	
    	xmlhttp.onreadystatechange=function()
    	{
    		//alert(xmlhttp.readyState);
    		//alert(xmlhttp.status);
    		if (xmlhttp.readyState == 4 && xmlhttp.status == 200) 
    		{
    			LoadXML(xmlhttp);
    			//document.getElementById('test').innerHTML=xmlhttp.responseText
    		}
    		else if (xmlhttp.status == 401)
    		{
    			alert('Access denied.');
    		}
    		else if (xmlhttp.status == 0)
    		{
    			alert('Cannot access cross domain information.');
    		}
    	}
    
    	xmlhttp.open("GET",url,true);
    	if(xmlhttp.timeout)
    	{
    		xmlhttp.timeout = 15000;
    		xmlhttp.ontimeout = timeoutFired;
    	}
    	xmlhttp.setRequestHeader("Cache-Control", "no-cache");
    	xmlhttp.send(null);
    }
    
    
    
    
    </script>
    </head>
    
    <body>
    
    
    
    <TABLE id="mytable" style="border-collapse: collapse;">
    <THEAD id="mytableheader" onclick="javascript:alert(this.parentNode.id);">
    	<TR>
    		<th>
    			Month
    		</th>
    		<th>
    			Savings
    		</th>
    	</TR>
    </THEAD>
    <TFOOT id="mytablefooter">
    	<TR>
    		<th colspan="2" style="text-align: left;">
    			...footer information...
    		</th>
    	</TR>
    </TFOOT>
    <TBODY id="firstBlock">
         <TR>
    		<td>...first row of block one data...</td>
    	</TR>
         <TR>
    		<td>
    			 ...second row of block one data...
    		</td>
    	 </TR>
    </TBODY>
    <TBODY id="secondBlock">
         <TR>
    		<td>
    			 ...first row of block two data...
    		</td>
    	 </TR>
         <TR>
    		<td>
    			...second row of block two data...
    		</td>
    	 </TR>
    </TBODY>
    </TABLE>
    
    
    <table id="newtable">
    </table>
    
    	<div>
    		<h2 id="test">
    			Click to let AJAX change this text
    		</h2>
    	</div>
    
    
    
    
    <script type="text/javascript" language="javascript">
    
    
    function ClearTable(strTableName)
    {
    	var target = document.getElementById(strTableName);
    	while (target.rows.length > 0) 
    	{
    		target.deleteRow(0);
    	}
    }
    
    
    
    function PopulateTable()
    {
    	ClearTable('mytable');
    	
    	
    	var div = document.createElement("DIV");
    	div.innerHTML = '<table id="tempTable" style="display: none"><tr style="background-color: red;"><td style="width: 50mm;">' + "lol" + '</td><td style="width: 50mm";>lol2</td></tr></table>';
    	var tt = div.getElementsByTagName('table')[0];
    
    	ClearTable('mytable');
    	var target = document.getElementById('mytable');
    	for(var i=0; i <tt.rows.length; i++)
    	{
    		target.appendChild(tt.rows[i]);
    		// target.appendChild(tt.rows[i].cloneNode(true));
    	}
    	
    	//div.parentNode.removeChild(div);
    	
    
    }
    
    
    </script>
    
    <!--
    <button type="button" onclick="loadXMLDocSynchronous('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton')">Synchro Cross-Domain</button>
    <button type="button" onclick="loadXMLDocAsynchronous('http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=Paris%20Hilton')">Async Cross-Domain</button>
    -->
    <button type="button" onclick="loadXMLDocSynchronous('txtxchange.txt')">Test Synchronos</button>
    <button type="button" onclick="loadXMLDocAsynchronous('cd_catalog.xml')">Test asynchronos</button>
    <button type="button" onclick="javascript:PopulateTable();">Populate Table</button><br>
    
    
    </body>
    </html>
    When you earnestly believe that you can compensate for a lack of skill by doubling your efforts, then there's no end to what you can't do...

  2. #2
    Coders muppetalert's Avatar
    Join Date
    Nov 2007
    Location
    Manchester, UK
    Posts
    1,006

    Re: Basic AJAJ

    Since IE7 Microsoft.XMLHTTP has been an alias for XMLHttpRequest() anyway, so you might aswell just use the following code to get your object. Wrap a try/catch around it if you really want to be semantic.. Supporting <IE6 is pointless since it probably won't suppor the rest of the DOM methods anyway.

    Code:
    var IE = /*@cc_on!@*/false;
    var http = (IE?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest());
    whiteLight: ET, whiteLight: Quake Live (Formerly QLHook) and many other game hacks at http://whitelight.me.uk/

  3. #3

    Re: Basic AJAJ

    Quote Originally Posted by muppetalert View Post
    Since IE7 Microsoft.XMLHTTP has been an alias for XMLHttpRequest() anyway, so you might aswell just use the following code to get your object. Wrap a try/catch around it if you really want to be semantic.. Supporting <IE6 is pointless since it probably won't suppor the rest of the DOM methods anyway.

    Code:
    var IE = /*@cc_on!@*/false;
    var http = (IE?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest());
    Didn't know about the alias. But IE7 > IE 6 > IE 5, and alias from IE >=7 and irrelevant < 6/5.5 , follows you forgot 6.0+ which is <7, that is to say the remote exploit IE version
    When you earnestly believe that you can compensate for a lack of skill by doubling your efforts, then there's no end to what you can't do...

  4. #4
    Coders muppetalert's Avatar
    Join Date
    Nov 2007
    Location
    Manchester, UK
    Posts
    1,006

    Re: Basic AJAJ

    Sorry that whole thing really made little sense to me

    The code I gave will work with IE6 and IE5.5 (due to the Microsoft.XMLHTTP object being valid), just saying that most of the other DOM methods you may be using in that code probably won't.
    whiteLight: ET, whiteLight: Quake Live (Formerly QLHook) and many other game hacks at http://whitelight.me.uk/

Similar Threads

  1. Basic v5 css
    By Hc4lNickNL in forum Counterstrike Source Cheat Downloads
    Replies: 3
    Last Post: May 20th, 2009, 15:03
  2. Visual Basic
    By SiLenCe in forum Visual Basic
    Replies: 0
    Last Post: July 24th, 2008, 00:23
  3. [TUTORIAL]Visual Basic[BASIC]
    By FreckleS in forum Basics
    Replies: 0
    Last Post: October 5th, 2007, 04:37
  4. [Basic]Alp[Tut]
    By Zero in forum Basics
    Replies: 12
    Last Post: October 4th, 2007, 22:52

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •