User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the JavaScript / DHTML / AJAX section within the Web Development category of DaniWeb, a massive community of 391,766 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 3,185 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our JavaScript / DHTML / AJAX advertiser: Lunarpages Web Hosting
Views: 5257 | Replies: 15
Reply
Join Date: Sep 2007
Location: Nevada, U.S.A.
Posts: 38
Reputation: HazardTW is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 1
HazardTW HazardTW is offline Offline
Light Poster

Re: AJAX generated <select> and FIREFOX

  #11  
Sep 13th, 2007
OK, here is an example, this one does not make an ajax request every time the country is changed, it only makes the request after page load, gets the countries and cities from the database and puts them in global variables.

The table name is test, the fields are "country" and "cities" where "country" is the country name, and "cities" is a comma delimited string of city names for that country.

Here is the PHP file that creates the XML response doc:
<?php
header('Content-Type: text/xml');
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
echo "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>\r";
echo "<response>\r\r";
//=============================================================================//
$dbconn = NULL;
function dbconnect($verbose=true) {
	global $dbconn;
	include('<usernames and pws come in here>');
	if (!$dbconn = @mysql_connect("localhost",$name,$pw)){return false;}
	if($verbose){echo "\r<!-- opening mysql connection -->\r";}
	return true;}
//=============================================================================//
$connection_open = dbconnect(false) or die("	<status>FAILED DBCONN</status>\r</response>");
@mysql_select_db("<name of your database>") or die("	<status>FAILED DBSELECT</status>\r</response>");
// ------------------------------------------------------------- //
echo "<status>SUCCESS</status>\r";

$sql = "SELECT * FROM test";
$result = @mysql_query($sql);
if ( !$result || !mysql_affected_rows())// if query failed OR no rows in the table output -- NONE --
{
	echo "<countries>-- NONE --</countries>\r";
}
else
{
	while ($row = @mysql_fetch_array($result))
	{
		echo "<countries>" . $row[country] . "|" . $row[cities] . "</countries>\r";
	}
	
}
//================================================================================================
echo "\r</response>";
if ($connection_open){@mysql_close($dbconn);}?>
With the data I put in the database table, the resulting XML doc looks like this:
<response>
<status>SUCCESS</status>
−
	<countries>
America|Los Angeles,New York,Miami,Dallas,Portland,Chicago,Casper
</countries>
−
	<countries>
Canada|Vancouver,Abbotsford,Armstrong,Burnaby,Castlegar,Chilliwack,Colwood,Coquitlam
</countries>
−
	<countries>
Mexico|Cancun,Cabo San Lucas,Los Cabos,San Jose del Cabo,Cozumel,Isla Mujeres,Riviera Maya,Acapulco
</countries>
</response>

Here is the HTML, tested it, it works:
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<script type="text/javascript">
<!--
function HttpClient() { } // HTTPCLIENT CLASS
HttpClient.prototype = {
	// type GET,POST passed to open
	requestType:'GET',
	// when set to true, async calls are made
	isAsync:true,
	// where an XMLHttpRequest instance is stored
	xmlhttp:false,
	// what is called when a successful async call is made
	callback:false,
	// what is called when send is called on XMLHttpRequest
	// set your own function to onSend to have a custom loading
	// effect
	onSend:function()
	{
		//document.getElementById('HttpClientStatus').style.display = 'block';
	},
	
	// what is called when readyState 4 is reached, this is
	// called before your callback
	onload:function()
	{
		//document.getElementById('HttpClientStatus').style.display = 'none';
	},
	
	// what is called when an http error happens
	onError:function(error)
	{
		alert(error);
	},
	
	// method to initialize an xmlhttpclient
	init:function()
	{
		try
		{
			// Mozilla / Safari
			this.xmlhttp = new XMLHttpRequest();
		}
		catch (e)
		{
			// IE
			var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
				 'MSXML2.XMLHTTP.4.0',
				 'MSXML2.XMLHTTP.3.0',
				 'MSXML2.XMLHTTP',
				 'Microsoft.XMLHTTP');
			var success = false;
			for (var i=0;i < XMLHTTP_IDS.length && !success; i++)
			{
				try
				{
					this.xmlhttp = new ActiveXObject
					(XMLHTTP_IDS[i]);
					success = true;
				}
				catch (e)
				{}
			}
			if (!success)
			{
				this.onError('Unable to create XMLHttpRequest.');
			}
		}
	},
	// method to make a page request
	// @param string url  The page to make the request to
	// @param string payload  What you're sending if this is a POST
	//                        request
	makeRequest: function(url,payload)
	{
		if (!this.xmlhttp)
		{
			this.init();
		}
		this.xmlhttp.open(this.requestType,url,this.isAsync);
		
		// set onreadystatechange here since it will be reset after a
		//completed call in Mozilla
		var self = this;
		this.xmlhttp.onreadystatechange = function()
		{
			self._readyStateChangeCallback();
		}
		if (this.requestType == "POST")
		{
			this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.xmlhttp.setRequestHeader("Content-length", payload.length);
			this.xmlhttp.setRequestHeader("Connection", "close");
		}
		
		this.xmlhttp.send(payload);
		
		if (!this.isAsync)
		{
			return this.xmlhttp.responseXML;
		}
	},
	
	// internal method used to handle ready state changes
	_readyStateChangeCallback:function()
	{
		switch(this.xmlhttp.readyState)
		{
			case 2:
				this.onSend();
				break;
			case 4:
				this.onload();
				if (this.xmlhttp.status == 200)
				{
					this.callback(this.xmlhttp.responseXML);
				}
				else
				{
					this.onError('HTTP Error Making Request: ' + '[' + this.xmlhttp.status + ']' + ' ' + this.xmlhttp.statusText);
				}
				break;
		}
	}
}
//----------------------------------------------------------------------------------------------------//

var client = new HttpClient();
client.isAsync = false;
var countries = "";
var cities = new Array();
http_status = null;

function get_country_city_list()
{
	client.requestType = "GET";
	// function to handle completed calls
	client.callback = function(XMLresult)
	{
		if (XMLresult.getElementsByTagName("status"))// did XML page create a 'status' element?
		{
			http_status = XMLresult.getElementsByTagName("status")[0].childNodes[0].nodeValue;
		}else{// if no 'status' element was returned, set global http_status to FAILED
			http_status = "FAILED NO RESPONSE";
			return;
		}
		if (http_status == "SUCCESS") {// if we got a SUCCESS in 'status' element, put row data in global variable
		
			// var results will be an array of all the <countries></countries> rows in the XML document
			var results = XMLresult.getElementsByTagName("countries");
			
			var comma = "";
			
			// I am going to make countries a comma delimited string of the country names
			countries = ""; // make sure we clear this global first
			
			for (var i=0; i<results.length; i++){// itterate through results
				
				// each row in results is formatted "countryname | city,city,city,city"
				// by spliting the result at the pipe we get a 2 element array
				//tmp[0]=country name  tmp[1]=string of cities
				var tmp = results[i].childNodes[0].nodeValue.split("|");
			
				countries += comma + tmp[0];// build the list of countries
			
				comma = ",";
			
				cities[tmp[0]] = tmp[1]; // use country name as key for cities array and assign the cityname string
			
			}			
		}
	}
	client.makeRequest('country_test.php?sid='+Math.random(),null);
	return;
}

function build_country_menu()
{
	http_status = null; // make sure this is cleared
	
	get_country_city_list() // make the ajax call
	
	if (http_status != "SUCCESS"){alert("something went wrong");return;}
	
	var cc = document.getElementById("country_menu");
	// remove all options from it
	while ( cc.options.length )
	{
		cc.remove(cc.options[0]);
	}
	
	var ctry = countries.split(",");
	
	for ( var i = 0; i < ctry.length; i++ )
	{
		// create new option element
		var newOpt=document.createElement('option');
		
		newOpt.text=ctry[i];
		// try adding the option to the select object
		try
		{
			cc.add(newOpt,null); // standards compliant
		}
		catch(ex)
		{
			cc.add(newOpt); // IE only
		}
		// set the value to same as the text
		cc.options[i].value = ctry[i];
	}
	// set selected index
	cc.selectedIndex = 0;
	build_city_menu(ctry[0]); // will need to rebuild the city list
}


function build_city_menu(country)
{
	var cs = document.getElementById("city_menu");
	// remove all options from it
	while ( cs.options.length )
	{
		cs.remove(cs.options[0]);
	}
	
	var cty = cities[country].split(",");
	
	for ( var i = 0; i < cty.length; i++ )
	{
		// create new option element
		var newOpt=document.createElement('option');
		
		newOpt.text=cty[i];
		// try adding the option to the select object
		try
		{
			cs.add(newOpt,null); // standards compliant
		}
		catch(ex)
		{
			cs.add(newOpt); // IE only
		}
		// set the value to same as the text
		cs.options[i].value = cty[i];
	}
	// set selected index
	cs.selectedIndex = 0;
}
-->
</script>
</head>

<body onload="build_country_menu()">

<select id="country_menu" onchange="build_city_menu(this.value)">
   <option></option>
</select>

<select id="city_menu">
   <option></option>
</select>

</body>
</html>

From this you should be able to extend it's capabilities to suit your needs, hopefully it's commented enough, I am bad about not commenting my work enough
Reply With Quote  
Join Date: Sep 2007
Posts: 25
Reputation: roy-- is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
roy-- roy-- is offline Offline
Light Poster

Re: AJAX generated <select> and FIREFOX

  #12  
Sep 14th, 2007
Spot on mate!

I really appreciate your time.

Although, in your example you assumed that I have the countries and cities in one table..

where as a matter of fact i have them in two seperate tables,

countries table: [countrycode] [name]

cities table: [countrycode] [city_id] [name] [nr_hotels]

What I need is to construct the options in a way that would show the city and number of hotels between brackets (i.e. London (45 hotels) )

I am sure there is a way of constructing this into the <countries> tag in your php script. Just not sure how! :s
Reply With Quote  
Join Date: Sep 2007
Location: Nevada, U.S.A.
Posts: 38
Reputation: HazardTW is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 1
HazardTW HazardTW is offline Offline
Light Poster

Re: AJAX generated <select> and FIREFOX

  #13  
Sep 15th, 2007
Your PHP file should be able to query more than one table to build your information and you can build a more complicated doc from it, I just try to keep it as simple as I can, I am complete rookie with XML and ajax.

If you first query your country table, get the list in an array $countries[] for example.
Then iterate through it, each pass using the country code to query your cities table.

Kind of like:

echo "<response>\r";
$countries = mysql_query("select * from countries");
while ($row = mysql_fetch_array($countries)){
     echo "<country>\r";
     echo "     <code>".$row[countryCode]."</code>\r";
     echo "     <name>".$row[countryName]."</name>\r";
     $sql = "select * from cities where countryCode = '$row[countryCode]'";
     $cities = mysql_query($sql);
     while ($cty = mysql_fetch_array($cities)){
          echo "<city>\r";
          echo "     <code>".$cty[cityCode]."</code>\r";
          echo "     <name>".$cty[cityName]."</name>\r";
          echo "     <hotels>".$cty[cityHotels]."</hotels>\r";
          echo "</city>\r";
     }
     echo "</country>\r";
}
echo "</response>";

I just wrote this here so I have not tried this code, but it should give you the idea.
If your country table had only one country and there were 4 cities in the cities table for that country code, the code above should result in a doc structure like this:

<response>
	<country>	
		<code>country code</code>		
		<name>country name</name>		
		<city>
			<code>city code</code>
			<name>city name</name>
			<hotels>number of hotels</hotels>
		</city>		
		<city>
			<code>city code</code>
			<name>city name</name>
			<hotels>number of hotels</hotels>
		</city>		
		<city>
			<code>city code</code>
			<name>city name</name>
			<hotels>number of hotels</hotels>
		</city>		
		<city>
			<code>city code</code>
			<name>city name</name>
			<hotels>number of hotels</hotels>
		</city>		
	</country>		
</response>
and a short bit of javascript to get at the values, I put no assignments in front of the references to each bit of data, how you assign them is up to you, whether you put them in arrays, or straight into form element values, etc...
// get array of all country tags
var records = XMLresult.getElementsByTagName("country");
// loop through them
for (var i=0; i<records.length; i++){
	// since records[i] points to an individual <country>, we can get it's children by tag name
	// first the country code
	records[i].getElementsByTagName("code")[0].childNodes[0].nodeValue;
	// then the country name
	records[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
	// now city will be an array of all the <city> tags
	var city = records[i].getElementsByTagName("city");
	// lets loop through them
	for (var z=0; z<city.length; z++){
		// get the city code
		city[z].getElementsByTagName("code")[0].childNodes[0].nodeValue;
		// the city name
		city[z].getElementsByTagName("name")[0].childNodes[0].nodeValue;
		// and the hotels for this city
		city[z].getElementsByTagName("hotels")[0].childNodes[0].nodeValue;
	}
}

There may be more proper and better ways of dealing with XML but like I said, I am a noob, and the above is about the extent of my knowledge about it and the easiest way for me to get the information I needed.
The examples I gave before where I put together long comma and ^ delimited strings is because a) I control the data so there are no characters in the data that would break the results and b) creating the multi level document structure makes for a pretty big file real quick and I want my responses as quick as they can be, don't know how much load time it saves but a 1k doc must load a lot quicker than a 40k doc eh?
I hope it helps
Last edited by HazardTW : Sep 15th, 2007 at 4:25 am. Reason: added comment
Reply With Quote  
Join Date: Sep 2007
Posts: 25
Reputation: roy-- is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 0
roy-- roy-- is offline Offline
Light Poster

Re: AJAX generated <select> and FIREFOX

  #14  
Sep 15th, 2007
Thanks alot man, will try and make this work now..
Reply With Quote  
Join Date: Jan 2007
Posts: 2,510
Reputation: MidiMagic is on a distinguished road 
Rep Power: 7
Solved Threads: 103
MidiMagic's Avatar
MidiMagic MidiMagic is offline Offline
Posting Maven

Re: AJAX generated <select> and FIREFOX

  #15  
Sep 18th, 2007
Anything that changes the HTML file from the original way it loads can cause the interpreter to fail, if the code is not valid. How the extra code is created does not matter.
Daylight-saving time uses more gasoline
Reply With Quote  
Join Date: Sep 2007
Location: Nevada, U.S.A.
Posts: 38
Reputation: HazardTW is an unknown quantity at this point 
Rep Power: 1
Solved Threads: 1
HazardTW HazardTW is offline Offline
Light Poster

Re: AJAX generated <select> and FIREFOX

  #16  
Sep 20th, 2007
haven't tried experimenting but the idea that came to mind was is you inadvertently appended a block level element as a child of an inline element where a validator would flag it as an error, would that type of invalid code cause problems when the doc type is strict.
Reply With Quote  
Reply

Only community members can participate in forum threads. You must register or log in to contribute.

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)

 

DaniWeb JavaScript / DHTML / AJAX Marketplace
Thread Tools Display Modes

Similar Threads
Other Threads in the JavaScript / DHTML / AJAX Forum

All times are GMT -4. The time now is 4:25 am.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC